2011-02-08 15 views
0

我想從我發佈一件東西到現在的那一刻過去的時間。我在我的模型類定義的方法:RubyOnRails中的時間差

class Post < ActiveRecord::Base 
validates :comment , :presence => true 

def time_past 
DateTime.now - self.created_at 

end 
end 

以下是錯誤:

IRB(主):001:0> Post.first.time_past 類型錯誤:預期數字或日期 從/ usr/lib/ruby​​/1.8/date.rb:1252:minus_without_duration' from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.3/lib/active_support/core_ext/date/calculations.rb:98:in - ' from /home/badescuga/proiecte/soundplace/app/models/post.rb:5:in`time_past' from(irb):1

回答

3

嘗試使用self.created_at而不是#{created_at}

+0

我已更正發佈的代碼,因爲您告訴我,但它仍然無效。在編輯中你也可以看到檢索到的錯誤 – Alex 2011-02-08 11:49:39

3

您可以使用此方法實現此目的。

def time_since_creation 
    Time.now - created_at 
end