ruby-on-rails Rails禁用devise flash消息

j8yoct9x  于 4个月前  发布在  Ruby
关注(0)|答案(7)|浏览(58)

如何禁用所有Devise gem flash消息(“成功登录”,“您已注销”)?谢谢。

i34xakig

i34xakig1#

也许最简单的方法就是
1.将每条消息定义为空字符串
1.在显示flash消息之前检查字符串的长度。
devise.en.yml文件中,将每条消息指定为空:

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

字符串
接下来,在布局中,在输出之前检查空白flash字符串。

<% flash.each do |key, value| %>
  <%= content_tag :div, value, :class => "flash #{key}" unless value.blank? %>
<% end %>

p1tboqfb

p1tboqfb2#

一个更适合我的答案是像这样覆盖Devise会话控制器

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

字符串
这将安全地覆盖删除flash消息的create和destroy方法

7lrncoxx

7lrncoxx3#

这项工作对我来说:

# 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,在这个例子中我只有一个devise模型。
我使用flash.discard(:notice),但你可以使用flash.discard来删除其他类型。(方法discard自rails 3.0起存在)
我更喜欢这种方法,因为它不是查看的角色来检查您的flash消息是否为空。如果您有flash消息,请打印它!如果您不想要,所以不要创建flash消息;-)

mwg9r5ms

mwg9r5ms4#

我已经能够通过覆盖is_flashing_format?在给定的控制器中禁用它们:

def is_flashing_format?
  false
end

字符串
我用的是Devise 3.5.6

iyfjxgzm

iyfjxgzm5#

对于Rails 5.0.6,此代码可以正常工作。
第一个月

class SessionsController < Devise::SessionsController

  def new
    flash.clear
    super
  end
end

字符串
不要忘记路线。
config/routes.rb
devise_for :users, controllers: { sessions: 'sessions' }

trnvg8h3

trnvg8h36#

从今天开始,只要留下一个空字符串就可以完全禁用吐司。这是有效的:

sessions:
  signed_in: ""
  signed_out: ""
  already_signed_out: ""

字符串

xmd2e60i

xmd2e60i7#

Devise包含一个方便的生成器,可以将所有视图复制到您的项目中:

rails generate devise:views

字符串
这样,您可以自己编辑视图,并决定要保留或丢弃哪些内容(Flash消息)。

相关问题