30

レコードに日時属性があります。

 1.9.3p194 :024> f.last_contact
 => Thu, 11 Aug 2011 00:00:00 UTC +00:00 

しかしtime_ago_in_words、コンソールで試してみると、うまくいきません:

> time_ago_in_words(f.last_contact)
NoMethodError: undefined method `time_ago_in_words' for main:Object

また、 Time、Date、DateTime オブジェクトでdistance_of_time_in_words動作するはずのドキュメントを試してみました。

> to_time = Time.now
 => 2012-09-08 12:22:16 -0500 
> distance_of_time_in_words(f.last_contact, to_time)
NoMethodError: undefined method `distance_of_time_in_words' for main:Object

これの原因は何ですか?Rails コンソールは、すべての Rails メソッドが機能するために必要なすべてのライブラリと依存関係をロードするべきではありませんか?

4

2 に答える 2

83

helperオブジェクトを介してすべてのヘルパー (組み込みおよび独自の) を使用できます

helper.time_ago_in_words(1.hour.ago)
=> "about 1 hour"

または必要なヘルパーをインポートする

include ActionView::Helpers::DateHelper
time_ago_in_words(1.hour.ago)
=> "about 1 hour" 
于 2012-09-08T17:37:39.317 に答える