Search code examples
ruby-on-railshttp-redirectviewruby-on-rails-5notice

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


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)?


Solution

  • 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.