2013-04-24 74 views
0

我正在嘗試使用「if語句」,它將最近發佈的評論與今天的created_at進行比較。爲什麼將created_at與當前日期進行比較會導致錯誤?

然而,這將返回錯誤:

應用助手

def chat_button(community) 
    if community.comments.last.created_at == Date.current.to_date 
    'Posted today' 
    else 
    'No post today' 
    end 
end 
+0

它返回什麼錯誤? – sosborn 2013-04-24 23:42:52

+0

@sosborn未定義的方法'created_at' – cat 2013-04-24 23:43:08

+2

community.comments.last正在返回一個零對象(如果您還沒有保存任何註釋,則可能會返回),或者您尚未正確聲明所有關聯(community has_many comments) – sosborn 2013-04-24 23:46:45

回答

2

你要比較一個DateTimecreated_at)到Date。小時/分鐘/秒將導致比較失敗。試試這個:

if community.comments.last.created_at.to_date == Date.current 
+0

非常感謝你 – cat 2013-04-25 00:11:45

+0

並感謝其他人解決'無'問題。 – 2013-04-25 00:16:04

1

還有一個簡短的方法來查看給定的日期時間是否是今天。

1.minute.ago.today? #=> true 
1.day.ago.today? #=> false 

你的情況,這將是:

comment = community.comments.last 
if comment && comment.created_at.today? 

注意,此方法是由Rails的活動提供支持,它不Ruby的標準庫中存在。

相關問題