开发者

url_for in controller

开发者 https://www.devze.com 2023-04-05 06:18 出处:网络
in a rails 2 controller i get some data from a model @company = Company.first and generate the url in the view

in a rails 2 controller i get some data from a model

@company = Company.first

and generate the url in the view

<%= 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 `mer开发者_如何学Goge': can't convert Company into Hash (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.

ActionController::Base has its own, similar (but not the same) method called url_for method. In the scope of your controller, the method defined on ActionController::Base is the one being called. 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. If you absolutely need or want the Rails 2.3 docs, you can download them here.


Those are not the same methods.

In your view, you're calling 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.

The url_for that you're calling in your script doesn't know how to do any of that. 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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消