Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link_to() in Rails flash

When a user fails login on my Rails app, I'd like 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.

like image 606
Grandpa Avatar asked Oct 21 '09 00:10

Grandpa


3 Answers

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)}" %>
like image 166
Baldu Avatar answered Nov 02 '22 22:11

Baldu


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
like image 26
Jan Avatar answered Nov 02 '22 23:11

Jan


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

like image 20
Daniel Fischer Avatar answered Nov 02 '22 23:11

Daniel Fischer