rails - Devise - Handling - devise_error_messages

2020-01-23 10:05发布

in my user edit page, there is a line as follows:

<%= devise_error_messages! %>

The problem is this does not output errors the standard way that the rest of the app does:

<% flash.each do |key, value| %>
    <div class="flash <%= key %>"><%= value %></div>
<% end %>

My question is, how do I get the devise error message to work like the others that use the flash.each?

Thanks.

20条回答
我命由我不由天
2楼-- · 2020-01-23 11:06

I came up to this and it's working so far. That adds devise messages to the flash, so it can be used as usual. Please consider that I'm new to Ruby and Rails...

class ApplicationController < ActionController::Base
  after_filter :set_devise_flash_messages, :if => :devise_controller?
  ...

  private:

  def set_devise_flash_messages
    if resource.errors.any?
      flash[:error] = flash[:error].to_a.concat resource.errors.full_messages
      flash[:error].uniq!
    end
  end
end

Edit:

Sorry I was running guard and some unwanted behavior was present. Since after_filter is called after the rendering so it doesn't work as expected. If someone know how to call a method after the action but before the rendering...

But you can use something like that instead:

module ApplicationHelper

  # merge the devise messages with the normal flash messages
  def devise_flash
    if controller.devise_controller? && resource.errors.any?
      flash.now[:error] = flash[:error].to_a.concat resource.errors.full_messages
      flash.now[:error].uniq!
    end
  end

end

In views/shared/_messages.html.erb

<% devise_flash %>
<!-- then display your flash messages as before -->
查看更多
做自己的国王
3楼-- · 2020-01-23 11:10

i simply do this, worked for me: in app/helpers/, i create a file devise_helper.rb

  module DeviseHelper

  def devise_error_messages_for(resource)
    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
end

in all view files i change

<%= devise_error_messages! %>

for:

<%= devise_error_messages_for(#your object in your formular)%>

for me it make in my view edit and new user:

  <%=form_for resource, as: @user, url: user_path(@user),...
      <%= devise_error_messages_for(@user) %>

hope it will help you ;)

查看更多
登录 后发表回答