Why do date helpers not work in Rails console?

醉酒当歌 提交于 2020-12-01 08:02:50

问题


I have a datetime attribute on a record:

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

But when I try time_ago_in_words at the console, it doesn't work:

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

I also tried distance_of_time_in_words which the docs say should work with Time, Date & DateTime objects.

> 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

What is the cause of this? Shouldn't Rails Console load all the necessary libraries and dependencies for all of Rails methods to work?


回答1:


You can use all helpers (built-in and your own) through helper object

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

Or import required helpers

include ActionView::Helpers::DateHelper
time_ago_in_words(1.hour.ago)
=> "about 1 hour" 



回答2:


Try

helper.time_ago_in_words(...)
helper.distance_of_time_in_words(...)

Calling helper. seems to give you access to any/all defined helpers.

More info in this answer: How do I call controller/view methods from the console in Rails?

The reason, I think, that you can't just call the helper directly is because they're not in scope from where you are (in the console), as opposed to code that's running inside a view where the helpers are in scope.



来源:https://stackoverflow.com/questions/12332899/why-do-date-helpers-not-work-in-rails-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!