link_to in models

Hi,

When I moved from Rails 2.1 to edge, I found that the old trick of putting

include ActionView::Helpers::UrlHelper # provides link_to include ActionController::UrlWriter # provides url_for

into models didn't work as well as it used to because of

Removed handling of string parameter in link_to to have all URL gener… · rails/rails@c98692a · GitHub

Prior to this commit, you could rely on link_to to return immediately when it saw a string like

link_to "Visit Other Site", "Ruby on Rails — A web-app framework that includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC) pattern.;

which effectively prevented it from passing non-hashes to ActionController::UrlWriter's url_for.

How do you solve the problem of using link_to (and rendering html in general) when you don't have a controller?

Am I missing an obviously better approach?

Thank you, Seamus

Prior to this commit, you could rely on link_to to return immediately when it saw a string like

link_to "Visit Other Site", "Ruby on Rails — A web-app framework that includes everything needed to create database-backed web applications according to the Model-View-Controller (MVC) pattern.;

which effectively prevented it from passing non-hashes to ActionController::UrlWriter's url_for.

What's the error that you see, url_for should just return the string shouldn't it?

How do you solve the problem of using link_to (and rendering html in general) when you don't have a controller?

This is still a little trickier than it could be, that's one of the key things that I hope we can get out of rails3's Action View changes. Yehuda's putting a stack of work into figuring out a nice, stable API for rendering. Hopefully we can give you something you could subclass and have a really easy job for generating HTML outside of controllers and mailers.

What's the error that you see, url_for should just return the string shouldn't it?

The error is "can't convert String into Hash." If I understand correctly, it's caused by a namespace collision due to the order of includes:

include ActionView::Helpers::UrlHelper # provides link_to (and also url_for) include ActionController::UrlWriter # provides url_for

So ActionView's link_to method actually calls ActionController's url_for directly, instead of the one that it itself defines.

Before the commit that I mentioned, this wasn't a problem, because both versions of url_for handled strings. The commit DRYs things up nicely for normal usage.

Finally, I don't think you can switch around the order of the includes, because ActionView's url_for depends on ActionController's url_for.

Thanks for your reply!

Seamus