link_to() in Rails flash
When a user fails login on my Rails app, I'd l开发者_开发问答ike to point them to a password reset page:
flash[:notice] = "Login failed. If you have forgotten your password, you can #{link_to('reset it', reset_path)}"
However, I can't use link_to in a controller. What's the best way to do this without mixing controller and view logic?
My best guess is that the flash is the wrong place to do this, but I'd appreciate any input.
I think the most common solution is to stick a link to the password reset page right in your login form, so your flash message doesn't have to deal with it at all. That also allows the user to request the reset without first failing to log in.
If you want to do it in the flash message, you should use url_for
to build the link instead of link_to
.
Alternatively, you could render a partial instead of hard-coding the message in your controller.
flash[:error] = render_to_string(:partial => "shared/login_failed_message")
# in shared/_login_failed_message.html.erb
<%= "Login failed. If you have forgotten your password, you can #{link_to('reset it', reset_path)}" %>
Today the best answer to this question might be (lifted from http://www.railsexperiments.com/using-helpers-inside-controllers)
flash[:notice] = "Login failed. If you have forgotten your password, you can #{view_context.link_to('reset it', reset_path)}".html_safe
flash[:notice] = "Login failed. If you have forgotten your password, you can <a href='#{url_for(reset_path)}'>reset it</a>"
Correct, link_to is a view helper. Please us a more generic way of building the link, à la url_for
精彩评论