2012-09-08 66 views
17

我有一個記錄日期時間屬性:爲什麼日期助手不能在Rails控制檯中工作?

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 

我也試過distance_of_time_in_words該文檔說應該工作與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 

這是什麼原因?不應該Rails控制檯加載所有Rails方法的所有必要的庫和依賴項的工作?

回答

54

您可以通過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" 
+0

完美!謝謝。 – marcamillion

+0

一百萬+1 – thedanotto

5

嘗試

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

調用helper.似乎給您訪問任何/所有定義的助手。在這個答案

更多信息:How do I call controller/view methods from the console in Rails?

究其原因,我認爲,你不能直接調用助手是因爲他們並沒有從範圍你是(在控制檯),其中,作爲而不是在幫助程序在範圍內的視圖內運行的代碼。

+0

'helper'工作。謝謝! – marcamillion

相關問題