How do I get flash[:notice] to display in my view?

3.1k Views Asked by At

I'm having difficulty getting my notices to display in my Rails 5 view. I have this before_filter method set up in a controller:

def check_email_confirmed!
  redirect_to controller: "users", action: "edit", notice: 'Please confirm your email.' unless current_user.email_confirmed
end

and in my view I have this

<% if flash[:notice] %>
  <p class="flash-notice"><%= flash[:notice] %></p>
<% end %>

but despite the fact that I know the notice is getting set (I see it in my URL) the above is not getting invoked in my view (I see no HTML with the class="flash-notice").

Is there some other way I should be setting flash notices in a redirect? Or should I be using a redirect at all (someone told me there might be some security risks in embedding messages in the URL query string)?

2

There are 2 best solutions below

0
On BEST ANSWER

You're currently setting a parameter with the key notice, not setting the flash in your session.

To accomplish this the way you're doing it you would have to do:

<p class="flash-notice"><%= params[:notice] %></p>

Most Rails apps that I've worked on set the session[:flash] in the controller method, in which case you would do:

unless current_user.email_confirmed
  redirect_to edit_user_path(current_user)
  flash[:notice] = 'Please confirm your email.'
end

Unless you have a good reason to pass the notice text as a URL param, I'd recommend doing it this way.

0
On

Try

flash[:notice] = 'bla'
redirect_to controller: "users", action: "edit"

I'm pretty sure that

redirect_to edit_user_path(user), notice: 'bla'

Will also work. For some reason your syntax apparently doesn't pick up the notice modifier. But you'll have to assign user to your current user for that to work obviously.