开发者

flash[:notice] not working in Rails

I have the following snippet of code in my controller

  def create
    @message = Message.new(params[:message])
    @message.message = h(@message.message)
    if @message.save
       flash[:message] = "Message Sent. Thank You for Contacti开发者_高级运维ng Me"
    else
       flash[:message] = "OOps Something went wrong"
    end
    redirect_to :action => 'contact'
  end

When I try to display the flash message in the contact form it doesnot display. I looked up possible solutions, but they dont seem to work. Any ideas what is going wrong?


Your controller is redirecting to :action => 'contact'. Ensure that the template being rendered for that action has the flash notice output.

<%= flash[:message] %>

Also, you may want to use render :action ... vs redirect_to :action .... Save yourself a request.


The flash hash can contain any set of messages you want to save until the next render. Scaffolds usually use the contents of flash[:notice] for notification messages. If you didn't use a scaffold to generate your web page you will have to add <%= flash[:notice]%> to your views.

You're setting flash[:message] in your controller. So it's not going to show up anywhere in your view unless your view contains <%= flash[:message]%> somewhere.

Your possible solutions are change all occurrences of flash[:message] to flash[:notice] in your controller or add <%= flash[:message]%> to any views that this action could render.


Not saying that you wouldn't have tried it, but if I were you I would do something down the lines like

<% if flash[:messsage].blank? %>
  <h1> flash hash is blank </h1>
<% end %>

If you see the "flash hash is blank" in your browser you know what it means.

EDIT:-

Something from the docs "Just remember: They‘ll be gone by the time the next action has been performed." Try this in your controller

flash.keep(:message) #keep the flash entry available for the next action


I recently ran into a scenario where flash messages will not be preserved. This scenario is when submitting a form which does not contain the CSRF token field. Rails will not be able to verify the CSRF token, so it will not preserve the flash messages. If you are using a plain HTML form, use the form_tag helper to automatically add this field for you.

<%= form_tag '/example/url' do %>
  <input name="example">
  <input type="submit" value="Submit the Form">
<% end %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜