简体   繁体   中英

Ruby on rails devise flash messages

I'm using devise gem in my application. After logging out i redirect user to the home page. When I go to log in page again, I see "You have been logged out" message from previous session. It happens even if I refresh my home page 20 times. Here's my devise_error_messages! method's code:

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

I'm using Rails 4.2.3, ruby 2.2.2 and devise 3.4.1. Is there any way to get rid of that old message? Any help would be appreciated. Thank you!

Maybe you could use an overrided devise_error_messages! method, adjusting it for your needs:

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

Also for better understanding of what's happening, you could place a breakpoint(binding.pry) in your code and check the flash array on the controller and view rendering: https://github.com/pry/pry

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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