如何加载UrlHelper和Rails中的路由?
我想在PORO中包含路由和link_to
方法。 在控制台中测试这个时,我遇到了这样的问题:
如果我在没有路由助手的情况下包含UrlHelper,一切似乎都可以正常工作:
ruby-1.9.3-rc1 :001 > Rails.version => "3.2.0.rc2" ruby-1.9.3-rc1 :001 > include ActionView::Helpers::UrlHelper => Object ruby-1.9.3-rc1 :002 > link_to "foo", Rails.application.routes.url_helpers.ponies_path => "foo"
如果我包含路线:
ruby-1.9.3-rc1 :001 > include ActionView::Helpers::UrlHelper ruby-1.9.3-rc1 :003 > include Rails.application.routes.url_helpers => Object ruby-1.9.3-rc1 :004 > link_to "foo", ponies_path
我收到以下错误:
NameError: undefined local variable or method `controller' for #
我在这做错了什么?
正如所建议的那样,你应该使用app
对象作为routes部分,你应该使用link_to的helper
对象。 使用控制台时,无需通过Ruby包含任何帮助程序:
helper.link_to "foo", app.ponies_path
使用app对象。
> link_to "foo", app.ponies_path