如何禁用所有 Devise gem flash 消息(“成功登录”、“您已注销”)?谢谢。
可能最简单的方法是
在您的
devise.en.yml
文件中,将每条消息指定为空:
en:
errors:
messages:
not_found: ''
already_confirmed: ''
not_locked: ''
等等。接下来,在布局中,在输出之前检查空白闪存字符串。
<% flash.each do |key, value| %>
<%= content_tag :div, value, :class => "flash #{key}" unless value.blank? %>
<% end %>
更适合我的答案是像这样覆盖设计会话控制器
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
这可以安全地覆盖创建和销毁方法,从而删除闪现消息
这对我有用:
# 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' }
我使用
Users::SessionsController
,但你可以使用SessionsController
,我在这个例子中只有一个设计模型。
我使用
flash.discard(:notice)
,但您可以使用flash.discard
同时删除其他类型。 (从rails 3.0开始就存在方法丢弃)
我更喜欢这种方法,因为检查 Flash 消息是否为空不是视图的作用。如果您有即时消息,请将其打印出来!如果您不希望,请不要创建即时消息 ;-)
我已经能够通过覆盖
is_flashing_format?
: 在给定的控制器中禁用它们
def is_flashing_format?
false
end
我正在使用 Devise 3.5.6
对于 Rails 5.0.6,此代码将有效。
app/controllers/sessions_controller.rb
class SessionsController < Devise::SessionsController
def new
flash.clear
super
end
end
不要忘记路线。
config/routes.rb
devise_for :users, controllers: { sessions: 'sessions' }
从今天开始,只需留下一个空字符串即可完全禁用 toast。 这有效:
sessions:
signed_in: ""
signed_out: ""
already_signed_out: ""
Devise 包含一个方便的生成器,可将所有视图复制到您的项目中:
rails generate devise:views
通过这种方式,您可以自己编辑视图并决定要保留或丢弃的内容(闪存消息)。