Emmanuel Oga’s Weblog

Using link_to, url_for, path methods from arbitrary places

Posteado por: emmanueloga en: Mayo 30, 2008

This is one thing I always forget, so I will post it to have it as reference.

If you need to call url_for or path methods (e.g.: root_path) from outside a controller, a view or a helper (perhaps inside a class lying somewhere inside RAILS_ROOT/lib/**/*), you will need to:

include ActionController::UrlWriter

If you also want to use link_to, you will need to:

include ActionView::Helpers::UrlHelper
include ActionController::UrlWriter

I include the two modules as I will probably want to use path methods in my link_to. Also notice that the UrlWriter module comes after the UrlHelper module.

“But it does not work!” I can hear you scream… If you get a message like this:

You have a nil object when you didn't expect it!
The error occurred while evaluating nil.url_for
(eval):17:in `project_stories_path'

Fear not, you may not have included the files in the right order. That message will appear if you include ActionController::UrlWriter before including ActionView::Helpers::UrlHelper. Just stick to the order I show above and the message will disappear.

5 comentarios para "Using link_to, url_for, path methods from arbitrary places"

You need to be careful with this. It can cause urls to render differently even if rendered from your views.

Specifically, if you access a page at an ip address eg.

http://192.168.1.4:3000/blah

url_for(…other…) called from a view should render as http://192.168.1.4:3000/other, but actually renders as http://localhost:3000/other

This can be a problem for xss. Not sure why this happens, but just caused me a lot of pain.

Thanks so much, you saved me hours of debugging! All I had to do was switch the order of the two includes as you have shown. Sweet!

To use link_to successfully in my controller, I also needed the following include:

include ActionView::Helpers::TagHelper

Without it, I received an “undefined method tag_options” error.

Great info, too bad the _path doesn’t work.?

I cant find any method_missing? in those helpers that catch the _path methods..

I echo Rob’s warning. This can cause some really weird bugs that can be next to impossible to debug.

Escribe un comentario