link_to() in Rails flash
Asked Answered
O

3

10

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.

Omegaomelet answered 21/10, 2009 at 0:43 Comment(0)
I
11

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)}" %>
Inoculum answered 21/10, 2009 at 3:30 Comment(2)
I find that this doesn't work (in Rails 3.1) because all output is escaped before being rendered. So you get something like "Listing saved to &lt;a href=&quot;/teams/1&quot;&gt;David Tuite's Team&lt;/a&gt;"Oslo
Just wanted to point out an alternative solution using view_context - #1332513Heater
I
6

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
Incubation answered 17/9, 2012 at 14:55 Comment(1)
This doesn't seem to work in Rails 6, unfortunately.Whirly
R
5
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

Regine answered 21/10, 2009 at 5:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.