How can I clear out the Rails flash object after responding to an Ajax request?

AKWF picture AKWF · Mar 18, 2013 · Viewed 8.9k times · Source

I am doing this type of thing for some of my controller actions:

def my_method

  flash[:notice] = "Success."

  respond_to do |format|
    format.js { render 'common/flashes' }
  end

end

And it works great, and the flash alerts and notices show up fine. But when the user clicks to go to another page, the flash messages show up one more time. Rails apparently doesn't know that they were used because of the way I'm handling them. How do I clear them out after doing the render above?

Answer

Mike Jarema picture Mike Jarema · Jan 30, 2016

Rahul's answer can be expressed more succinctly in application_controller.rb or any other controller as:

after_action -> { flash.discard }, if: -> { request.xhr? }

This takes advantage of ActionController's handling of lambdas and conditional filters.