link_to() in Rails flash

2020-03-12 05:27发布

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.

3条回答
男人必须洒脱
2楼-- · 2020-03-12 06:06
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

查看更多
不美不萌又怎样
3楼-- · 2020-03-12 06:10

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)}" %>
查看更多
倾城 Initia
4楼-- · 2020-03-12 06:24

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
查看更多
登录 后发表回答