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:
If you also want to use link_to, you will need to:
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
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.