ruby-on-railsangularjsdeviserails-flash

How to force Rails to abandon flash messages when transitioning to Angularjs?


Currently I am developing a site that uses a pure angularjs single page js application backed by rails. The only thing that is still using rails views are the devise pages for login,password reset, etc. Once the user is logged in, I forward them to angularjs url. However, when the user logs out, they are returned to rails signin page where they see a very stale flash message.

I was thinking I can just have Angular do a $http ping to rails controller which forces rails to do flash.clear(). But this doesn't seem to work. When I logout, the last devise message is still there.


Solution

  • I would recommend clearing hash inside your application controller unless it is devise controller so you dont need to do extra http rest call for that. Here is what you can do

    in your application_controller.rb add before filter that clears flash unless it is a devise controller:

    before_filter :discard_flash, :unless => :devise_controller?
    
    private
    
    def discard_flash
      flash.discard              # discard the entire flash at the end of the current action
      flash.discard(:warning)    # discard only the "warning" entry at the end of the current action
    end
    

    now when a user is interacting with your application, flash object will be discarded if it is not a devise controller, so you will still show flash messages if user types wrong password... if user signs in successfully and hits non devise controller, then flash object will be discarded. for api reference please look at following links: http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html and http://rubydoc.info/github/plataformatec/devise/master/Devise/Controllers/Helpers