Rails - 设计 - 登录时出现错误消息?

Fre*_*xuz 35 ruby-on-rails devise

如何让f.error_messages在这里工作,或者我应该使用闪光灯?
如果是这样,在sessions_controller中应该覆盖什么?

<h2>Create an account</h2>    
<% form_for resource_name, resource, :url => registration_path(resource_name) do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :email %><br />
    <%= f.text_field :email, :class => :big %>
  </p>
  <p>
    <%= f.label :password %><br />
    <%= f.password_field :password, :class => :big %>
  </p>
  <p>
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, :class => :big %>
  </p>

  <p><%= f.submit "Create", :class => :submit %></p>
<% end %>
Run Code Online (Sandbox Code Playgroud)

PS.创建帐户的f.error_messages完全正常.

ffo*_*oeg 65

尝试将这些放在你的布局中:

<%= content_tag(:div, flash[:error], :id => "flash_error") if flash[:error] %>
<%= content_tag(:div, flash[:notice], :id => "flash_notice") if flash[:notice] %>
<%= content_tag(:div, flash[:alert], :id => "flash_alert") if flash[:alert] %>
Run Code Online (Sandbox Code Playgroud)

Devise中的登录操作设置了闪存消息,而不是模型错误.

  • 好.:登录后通知工作正常,但似乎根本没有设置错误/警报.. (3认同)
  • 为什么设置闪存消息而不是模型错误?鉴于其验证失败,我期望模型错误. (3认同)
  • 2016 年,这就像 2011 年一样。所以这里的问题是:如果您将 Flash 消息放置在布局中,如何强制它们出现在“&lt;h2&gt;登录&lt;/h2&gt;”和“&lt;登录页面上的 form&gt;...&lt;/form&gt;`? (2认同)

typ*_*ror 31

不可否认,有点hacky,但我正在使用这个助手(app/helpers/devise_helper.rb)来获取闪存并使用那些设置然后默认为resource.errors.

module DeviseHelper

  def devise_error_messages!
    flash_alerts = []
    error_key = 'errors.messages.not_saved'

    if !flash.empty?
      flash_alerts.push(flash[:error]) if flash[:error]
      flash_alerts.push(flash[:alert]) if flash[:alert]
      flash_alerts.push(flash[:notice]) if flash[:notice]
      error_key = 'devise.failure.invalid'
    end

    return "" if resource.errors.empty? && flash_alerts.empty?
    errors = resource.errors.empty? ? flash_alerts : resource.errors.full_messages

    messages = errors.map { |msg| content_tag(:li, msg) }.join
    sentence = I18n.t(error_key, :count    => 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
Run Code Online (Sandbox Code Playgroud)

  • 哈克?你太谦虚了,这真的很有帮助. (5认同)

Car*_*rds 5

尽管这篇文章已经很久了,但我想分享一个解决方案来帮助像我这样开始使用Devise时遇到麻烦的人.为了保持干燥,我刚刚在我的application.html.erb文件中插入此代码:

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

  <%= yield %>
</body>
Run Code Online (Sandbox Code Playgroud)