Rails Disable devise flash messages
How I can disable all Devise gem flash messages ("successfully signe开发者_运维技巧d in","you logged out")? Thanks.
Probably the easiest way to do this is to
- Define each message as a blank string
- 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 %>
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
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 ;-)
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
For Rails 5.0.6 this code will work.
app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
def new
flash.clear
super
end
end
Do not forget the routes.
config/routes.rb
devise_for :users, controllers: { sessions: 'sessions' }
Devise includes a handy generator to copy all the views into your project:
rails generate devise:views
This way you can edit the views yourself and decide what you want to keep or throw away (flash messages).
精彩评论