简体   繁体   English

如何加载UrlHelper和Rails中的路由?

[英]How can I load UrlHelper and the routes in the Rails?

I want to include the routes and the link_to method in a PORO. 我想在PORO中包含路由和link_to方法。 While testing this in the console I came accross this: 在控制台中测试时,我遇到了这样的问题:

If I include UrlHelper without the routes helper everything seems to work fine: 如果我在没有路由助手的情况下包含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
 => "<a href=\"/ponies\">foo</a>" 

If I include the routes: 如果我包含路线:

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

I get the following error: 我收到以下错误:

NameError: undefined local variable or method `controller' for #<ApplicationController:0x007fa1497ecc40>

What am I doing wrong here? 我在这做错了什么?

As suggested you should use the app object for the routes part and you should be using the helper object for the link_to. 正如所建议的那样,你应该使用app对象作为routes部分,你应该使用link_to的helper对象。 No need to include any of the helpers through Ruby when using the console: 使用控制台时,无需通过Ruby包含任何帮助程序:

helper.link_to "foo", app.ponies_path

使用app对象。

> link_to "foo", app.ponies_path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM