Rails Flash message is not shown
I have a line in a controller that will redirect to the home screen with a custom flash message, like so:
redirect_to :contr开发者_JAVA技巧oller => :home, :action => :index, :alert => "You are not yet assigned to an experiment." and return
The user is then redirected to the following page: http://localhost:3000/home?alert=You+are+not+yet+assigned+to+an+experiment
However, the flash message is not shown, although all other flash messages work in my application. The views/layouts/application.html.erb file contains the following:
<div class="flash">
<%- if !notice.nil? -%>
<p class="notice"><%= notice %></p>
<%- end -%>
<%- if !alert.nil? -%>
<p class="alert"><%= alert %></p>
<%- end -%>
</div>
What am I doing wrong here?
Flash is using session to store messages
flash[:alert] = "You are not yet assigned to an experiment."
redirect_to :controller => :home, :action => :index and return
<%= flash[:alert] %>
If you want to pass it through params you should use params[:param_name]
redirect_to :controller => :home, :action => :index, :alert => "You are not yet assigned to an experiment." and return
<%= params[:alert] %>
Flash is more preferable, it works implicitly across pages and is cleared after it's shown
In your view, you access a notice flash message by using
<%= flash[:notice] %>
not
<%= notice %>
The same applies to alert.
Also, there's an error in your code.
redirect_to :controller => :home, :action => :index, :alert => "You are not yet assigned to an experiment."
must be
redirect_to({ :controller => :home, :action => :index }, :alert => "You are not yet assigned to an experiment.")
精彩评论