简体   繁体   English

控制器中的url_for

[英]url_for in controller

in a rails 2 controller i get some data from a model 在Rails 2控制器中,我从模型中获取了一些数据

@company = Company.first

and generate the url in the view 并在视图中生成URL

<%= url_for @company %>

Of course this works fine. 当然可以。 But when i try to use this in a script 但是当我尝试在脚本中使用它时

include ActionController::UrlWriter
default_url_options[:host] = 'www.example.com'

@company = Company.first
puts url_for(@company)

it fails with 它失败了

/gems/actionpack-2.3.8/lib/action_controller/url_rewriter.rb:127:in `merge': can't convert Company into Hash (TypeError) /gems/actionpack-2.3.8/lib/action_controller/url_rewriter.rb:127:在“合并”中:无法将公司转换为哈希(TypeError)

Any ideas? 有任何想法吗?

I think the issue might be that the url_for method that you're used to calling in your views ( and defined on ActionView as a helper ) is not the same url_for method that gets called when you're in a controller. 我认为这个问题可能是, url_for ,你用来调用你的意见(方法和定义上的ActionView为助手 )是一样的url_for当你在一个控制器是被调用的方法。

ActionController::Base has its own, similar (but not the same) method called url_for method. ActionController::Base有自己的相似(但不相同)的方法,称为url_for方法。 In the scope of your controller, the method defined on ActionController::Base is the one being called. 在您的控制器范围内,在ActionController::Base上定义的方法就是被调用的方法。 http://apidock.com/rails/ActionController http://apidock.com/rails/ActionController

The link to ActionController docs above technically points to the Rails3 version of the API, but it hasn't really changed. 上面的ActionController文档链接在技术上指向该API的Rails3版本,但实际上并没有改变。 If you absolutely need or want the Rails 2.3 docs, you can download them here . 如果您绝对需要或需要Rails 2.3文档,可以在此处下载它们

Those are not the same methods. 那些方法不一样。

In your view, you're calling ActionView::Helpers::UrlHelper#url_for . 在您的视图中,您正在调用ActionView::Helpers::UrlHelper#url_for That method has several checks in it to decide what to do based on the type of data that you passed in. If you pass in a model object you end up in the method ActionController::PolymorphicRoutes#polymorphic_path which figures out which named route it's supposed to be using. 该方法有几项检查,以根据传入的数据类型来决定要执行的操作。如果传入模型对象,则最终会到达方法ActionController::PolymorphicRoutes#polymorphic_path ,该方法会找出应该使用的命名路由被使用。

The url_for that you're calling in your script doesn't know how to do any of that. 您在脚本中调用的url_for不知道该怎么做。 However, it can still do quite a bit and I would suggest that you read the comments in that file for ideas on how to use it. 但是,它仍然可以做很多工作,我建议您阅读该文件中的注释,以获取有关如何使用它的想法。 The error message that you got will point you right to it. 您收到的错误消息将使您直接找到它。

/gems/actionpack-2.3.8/lib/action_controller/url_rewriter.rb

(Note: actionpack 2.3.14 is available. You might want to upgrade while you're at it.) (注意:actionpack 2.3.14可用。您可能需要在升级时进行升级。)

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

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