8

I'm using Devise.
When the user succeeded at confirmation, the flash message appears.
I'd like to add a link to it.

So I want this message instead

Your account was successfully confirmed. You are now signed in. Go to your profile page, and edit it!

Then the part of profile should be the link to example.com/users/username/edit

How can I make it possible?

devise.en.yml

confirmations:
  confirmed: 'Your account was successfully confirmed. You are now signed in.'
HUSTEN
  • 5,117
  • 4
  • 24
  • 38
  • http://stackoverflow.com/questions/4008059/rails-devise-customize-flash-message-devise-en-yml-with-a-link-to?rq=1 – Nick Ginanto Mar 24 '13 at 10:02
  • 1
    By the way: When working without devise and you have controllers you can use the method [`view_context`](http://api.rubyonrails.org/classes/ActionView/Context.html) to access any view method inside your models or controllers. E.g.: `view_context.link_to("link text", link_path)` – Dennis Hackethal Mar 24 '13 at 10:10
  • @Charles That's great to hear about that. Thanks:) Could you please put that as an answer? – HUSTEN Mar 24 '13 at 10:26

2 Answers2

13

You can use the method view_context to access any view method inside your models and controllers.

For example:

def index
  flash[:notice] = "Go to your #{view_context.link_to("profile page", link_path)}, and edit it!"
  redirect_to link_path
end

Update link_path accordingly.

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
  • 5
    When I used this method, I had to attach .html_safe at the end of the message string. Without that, the anchor tag and its contents showed as plain-text on the page. – Ege Ersoz Apr 23 '14 at 23:57
  • Does not work with Rails 5.0. Even with `.html_safe`. – the12 Jun 27 '17 at 04:19
  • 1
    Yeah, that's interesting... I wonder what changed. When I call `html_safe` on the flash message *inside the template*, then it works. Such as `<%= notice.html_safe %>`. I wonder why, though. – Dennis Hackethal Jul 10 '17 at 05:26
4

I had trouble implementing these solutions. All I needed was a simple HTML link in the flash. Here's how I implemented it in Rails 4.1. I just had to sanitize my flash messages in app/views/shared/_flash.html.erb:

<% flash.each do |name, msg| %>
  <div class="alert alert-<%= name %>">
    <a class="close" data-dismiss="alert">&#215</a>
    <% if msg.is_a?(String) %>
      <div id="flash_<%= name %>"> <%= sanitize(msg) %> </div>
    <% end %>
  </div>
<% end %>

And in my controller, I just entered HTML directly and without .html_safe. Works a treat!

flash[:notice] = %Q[Please <a href="#">click here</a>]
bryanus
  • 954
  • 1
  • 8
  • 11