Shiv
Shiv

Reputation: 8412

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

Upvotes: 3

Views: 25890

Answers (4)

Andrew
Andrew

Reputation: 238717

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 %>

Upvotes: 1

EmFi
EmFi

Reputation: 23450

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.

Upvotes: 5

Anand Shah
Anand Shah

Reputation: 14913

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

Upvotes: 3

nowk
nowk

Reputation: 33171

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.

Upvotes: 16

Related Questions