RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

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

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?

Upvotes: 14

Views: 12939

Answers (4)

Mike Jarema
Mike Jarema

Reputation: 1187

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.

Upvotes: 17

For cleaning all flashes use flash.clear instead of flash.discard

https://api.rubyonrails.org/v5.1.7/classes/ActionDispatch/Flash/FlashHash.html#method-i-clear

Upvotes: 14

stackPusher
stackPusher

Reputation: 6512

Neither of these answers worked for me on rails 5.2. After calling flash.discard i still had a flash message. Instead I had to call flash[:notice] = nil

Upvotes: 6

Rahul garg
Rahul garg

Reputation: 9362

In your application_controller.rb

after_filter :clear_xhr_flash


def clear_xhr_flash
  if request.xhr?
    # Also modify 'flash' to other attributes which you use in your common/flashes for js
    flash.discard
  end
end

Upvotes: 6

Related Questions