繁体   English   中英

Ruby on Rails设计Flash消息

[英]Ruby on rails devise flash messages

我在应用程序中使用了devise gem。 注销后,我将用户重定向到主页。 当我再次进入登录页面时,看到上一会话的消息“您已注销”。 即使我刷新主页20次,也会发生这种情况。 这是我的devise_error_messages! 方法的代码:

def devise_error_messages!
flash_errors = []
flash_notices = []

if !flash.empty?
  flash_errors.push(flash[:error]) if flash[:error]
  flash_errors.push(flash[:alert]) if flash[:alert]
  flash_notices.push(flash[:notice]) if flash[:notice]
end

return "" if resource.errors.empty? && flash_errors.empty? && flash_notices.empty?

# not important output styling
errors = resource.errors.empty? ? flash_errors : resource.errors.full_messages
error_icon = "<span class=\"glyphicon glyphicon-exclamation-sign\" aria-hidden=\"true\">&nbsp;</span>"
errors = errors.map { |msg| "<p>" + error_icon + msg + "</p>" }.join
errors = "<div class=\"alert alert-danger\" role=\"alert\">" + errors + "</div>" unless errors.empty?

notice_icon = "<span class=\"glyphicon glyphicon-ok\" aria-hidden=\"true\">&nbsp;</span>"
notices = flash_notices.map { |msg| "<p>" + notice_icon + msg + "</p>" }.join
notices = "<div class=\"alert alert-success\" role=\"alert\">" + notices + "</div>" unless notices.empty?

html = <<-HTML
<div id="error_explanation">
  #{errors}
  #{notices}
</div>
HTML

html.html_safe
end

我正在使用Rails 4.2.3,ruby 2.2.2和设计3.4.1。 有什么办法可以摆脱那条旧信息? 任何帮助,将不胜感激。 谢谢!

也许您可以使用覆盖的devise_error_messages! 方法,根据您的需要进行调整:

module DeviseHelper
  def devise_error_messages!
    return "" if resource.errors.empty?

    messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
    sentence = I18n.t("errors.messages.not_saved",
                      :count => resource.errors.count,
                      :resource => resource.class.model_name.human.downcase)

    html = <<-HTML
    <div id="error_explanation">
      <h2>#{sentence}</h2>
      <ul>#{messages}</ul>
    </div>
    HTML

    html.html_safe
  end

  def devise_error_messages?
    resource.errors.empty? ? false : true
  end

end

另外,为了更好地了解正在发生的事情,您可以在代码中放置一个断点(binding.pry)并检查控制器上的闪存阵列并查看渲染: https : //github.com/pry/pry

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM