RubyOnRails:如何在Rails控制台中使用辅助方法?

时间:2012-10-17 20:28:04

标签: ruby-on-rails ruby ruby-on-rails-3 irb actionviewhelper

我的设置可能有问题:

irb(main):001:0> truncate("Once upon a time in a world far far away", :length => 17)
NoMethodError: undefined method `truncate' for main:Object
        from (irb):1
        from /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:47:in `start'
        from /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:8:in `start'
        from /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

看起来我不能使用任何文本助手(在irb和rails控制台中)。

我应该检查什么?

2 个答案:

答案 0 :(得分:22)

Rails控制台通过helper变量公开辅助方法。因此,请使用此代码:

helper.truncate("Once upon a time in a world far far away", :length => 17)

了解更多信息,请阅读此article on 37signals.com

答案 1 :(得分:2)

在您的rails控制台中键入以下行

include ActionView::Helpers

现在您的帮助程序在整个rails控制台会话期间都可以访问,您可以继续... ...

truncate("Once upon a time in a world far far away", :length => 17)