开发者

flash notice persisting in rails controller

开发者 https://www.devze.com 2023-04-13 07:33 出处:网络
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 fl

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 updat开发者_JAVA百科ed"
      format.html{ render :action => "edit" }
    else
      format.html{ render :action => "edit" }
    end
  end
end  


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.


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.

0

精彩评论

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

关注公众号