如何在 Rails 中加载 UrlHelper 和路由? [英] How can I load UrlHelper and the routes in the Rails?

查看:38
本文介绍了如何在 Rails 中加载 UrlHelper 和路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 PORO 中包含路由和 link_to 方法.在控制台中测试时,我遇到了这个:

I want to include the routes and the link_to method in a PORO. While testing this in the console I came accross this:

如果我在没有路由助手的情况下包含 UrlHelper,一切似乎都正常:

If I include UrlHelper without the routes helper everything seems to work fine:

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>" 

如果我包括路线:

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 #<ApplicationController:0x007fa1497ecc40>

我在这里做错了什么?

推荐答案

建议你应该使用 app 对象作为路由部分,你应该使用 helperlink_to 的对象.使用控制台时无需通过 Ruby 包含任何帮助程序:

As suggested you should use the app object for the routes part and you should be using the helper object for the link_to. No need to include any of the helpers through Ruby when using the console:

helper.link_to "foo", app.ponies_path

这篇关于如何在 Rails 中加载 UrlHelper 和路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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