3
votes

I've got a controller with an update method that updates the model attribute, sets a flash notice for the user if successful and then renders the edit page again. The next link I click on the same flash notice pops up a second time when it loads/renders the page. What's going on? How do I get the flash[:notice] to show up only once? Why is it persisting into the next response?

controller:

def update
  respond_to do |format|
    if @resource.update_attributes(params[:resource])
      flash[:notice] = "Resource successfully updated"
      format.html{ render :action => "edit" }
    else
      format.html{ render :action => "edit" }
    end
  end
end  
2

2 Answers

12
votes

If you want the flash notification to be displayed immediately, use flash.now[:notice] instead of flash[:notice]. The default behavior is to save the flash until the subsequent request is processed, where the now version will clear it after the current request is finished.

2
votes

You should not be using render method after a successful edition. Instead try using redirect_to:

respond_to do |format|
    if @resource.update_attributes(params[:resource])
        flash[:notice] = "Resource successfully updated"
        format.html{ redirect_to :action => edit, :id => @resource }
    else
        format.html{ render :action => "edit" }
    end
end

Check Rails Guide for more information about the differences between those two methods.