为什么日期助手在 Rails 控制台中不起作用? [英] Why do date helpers not work in Rails console?

查看:50
本文介绍了为什么日期助手在 Rails 控制台中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在记录上有一个日期时间属性:

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 

但是当我在控制台尝试 time_ago_in_words 时,它不起作用:

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

我也尝试过 distance_of_time_in_words 文档说应该与 时间、日期和日期时间对象.

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

这是什么原因?Rails Console 不应该为所有 Rails 方法加载所有必需的库和依赖项吗?

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

推荐答案

您可以通过 helper 对象使用所有帮助程序(内置的和您自己的)

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

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" 

这篇关于为什么日期助手在 Rails 控制台中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆