Leahcim
Leahcim

Reputation: 41919

Rails: on redirect to same page form submitted from, flash message not showing

on form submission to "create" action in the sexes_controller, I've changed things to actually redirect back to the page views/results/index that the form was submitted from, but now the flash message is not displaying even though I'm doing

<%= flash[:notice] %>

at the bottom of views/results/index (i.e. the page the form was submitted from), which is how I assume you're supposed to do it.

Is it because there's some sort of caching that's taking place that the flash message is not showing up? Any idea how to get around that?

Update

thinking it might be more complicated, I've tried to retrieve the flash message in the index action of the results controller

@flashbash = Sex.find(params[:id])

and then back in views/results/index

<%= if @flashbash flash[:notice] %>  (I think this code is wonky)

note, I tried this, but it didn't work. It said, Couldn't find Sex without an ID

Any ideas how I can fix this?

Upvotes: 3

Views: 7685

Answers (1)

Ben Simpson
Ben Simpson

Reputation: 4049

Typically the flash is rendered in the application's layout file. This avoids the duplication of having to output <%= flash[:notice] %> in every view that could potentially have a flash message.

As to why its not showing up check that you are setting your flash[:notice] variable with something to display. An example of a create action in a controller may look like this:

# app/controllers/sex_controller.rb
def create
  @sex = Sex.new(params[:sex])
  if @sex.save
    flash[:notice] = "Saved successfully"
    redirect_to @sex # This redirects to the show action, where the flash will be displayed
  else
    flash[:error] = "There were errors..."
    render :action => :new # This displays the new form again
  end
end

# app/layouts/application.html.erb
<html>
  ...
  <%= flash[:notice] %>
  <%= flash[:error] %>
  <%= yield %>
  ...
</html>

More information on flash messages here: http://guides.rubyonrails.org/action_controller_overview.html#the-flash

Upvotes: 7

Related Questions