Devise errors are displayed twice

2019-08-03 16:38发布

问题:

Using Devise for authorization I configured it to authorize by email or login. Validatable driver deleted. I wrote validates in my user model. Also I overwrite devise helper in app/helpers/devise_helper.rb:

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

    errors = Array.new

    resource.errors.each do |field, msg|
      errors.push(msg)
    end
    flash[:alert] = errors
  end
end

In view (devise/registrations/new.html.erb) I replace

<%= devise_error_messages! %>

to

<% devise_error_messages! %>

So, problem. When fields are empty (or else), flash errors are showing. Then I go to main page, and errors show again. It's appear only in registration interface. When authorization thats all right. Please help.

Updated.

partial view (_block_errors.html.erb):

<% flash.each do |name, msg| %>
  <% if msg.class == Array %>
    <% msg.each do |message| %>
      <%= content_tag :p, message, :class => "#{name}" %>
    <% end %>
  <% else %>
    <%= content_tag :p, msg, :class => "#{name}" %>
  <% end %>
<% end %>

In layout it's called like:

<%= render 'layouts/block_errors' %>

Solved!

In overloaded method devise_error_messages! need to replace string:

flash[:alert] = errors

to

flash.now[:alert] = errors

Hope it helps anybody :)

回答1:

Are you sure you don't have alert displayed anywhere else in your app?

Should look something like this

<% if flash[:alert] %>
  <p id="notice"><%= flash[:alert] %></p>
<% end %>


回答2:

I resolved the problem by deleting <p id="notice"><%= notice %></p> in my the index.html.erb file