【问题标题】:Ruby on rails devise flash messagesRuby on rails 设计了 ​​flash 消息
【发布时间】:2016-05-31 23:46:13
【问题描述】:

我在我的应用程序中使用了 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。有没有办法摆脱那个旧消息?任何帮助,将不胜感激。谢谢!

【问题讨论】:

  • 我认为 flash_alerts = [] 需要在顶部和 flash_alerts.push(flash[:alert]) if flash[:alert]
  • 我不在任何地方使用 flash_alerts 数组,我将 flash[:alerts] 推送到 flash_errors 数组。这是我需要使用的一些修改,与主要问题无关
  • 在flash的assignements后面加上flash.clear

标签: ruby-on-rails ruby ruby-on-rails-3 devise


【解决方案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

【讨论】:

    猜你喜欢
    • 2011-07-08
    • 2011-11-26
    • 1970-01-01
    • 2016-06-17
    • 2014-04-28
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 2011-10-07
    相关资源
    最近更新 更多