Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Disable devise flash messages

How I can disable all Devise gem flash messages ("successfully signed in","you logged out")? Thanks.

like image 421
Marat_Galiev Avatar asked Apr 23 '11 07:04

Marat_Galiev


4 Answers

Probably the easiest way to do this is to

  1. Define each message as a blank string
  2. Check the length of the string before you show a flash message.

In your devise.en.yml file, specify each message as empty:

en:
  errors:
    messages:
      not_found: ''
      already_confirmed: ''
      not_locked: ''

etc. Next, in your layout, check for blank flash strings before you output them.

<% flash.each do |key, value| %>
  <%= content_tag :div, value, :class => "flash #{key}" unless value.blank? %>
<% end %>
like image 199
Michelle Tilley Avatar answered Oct 28 '22 07:10

Michelle Tilley


An answer better suited for me was to override the Devise Session Controller like this

class SessionsController < Devise::SessionsController

  # POST /resource/sign_in
  def create
    super
    flash.delete(:notice)
  end

  # DELETE /resource/sign_out
  def destroy
    super
    flash.delete(:notice)
  end

end

This safely overrides the create and destroy method removing the flash message

like image 37
acrogenesis Avatar answered Oct 28 '22 06:10

acrogenesis


This work for me:

# app/controllers/users/sessions_controller.rb
class Users::SessionsController < Devise::SessionsController
  after_action :remove_notice, only: [:destroy, :create]

  private

  def remove_notice
    flash.discard(:notice) #http://api.rubyonrails.org/v5.1/classes/ActionDispatch/Flash/FlashHash.html#method-i-discard
  end
end

# add this line in 'config/routes.rb'
devise_for :users, :controllers => { sessions: 'users/sessions' }

I use Users::SessionsController but you can use SessionsController, I have just one devise model in this example.

I use flash.discard(:notice) but you can use flash.discard to remove others types in same time. (method discard exist since rails 3.0)

I prefer this approach, because it's not the role of the view to check if your flash message if blank. If you have a flash message, print it! If you don't want, so don't create flash message ;-)

like image 8
jpheos Avatar answered Oct 28 '22 05:10

jpheos


I've been able to disable them in a given controller by overriding is_flashing_format?:

def is_flashing_format?
  false
end

I'm using Devise 3.5.6

like image 7
Manuel Pedrera Avatar answered Oct 28 '22 07:10

Manuel Pedrera