如何使用类自定义设计错误消息

即时通讯使用twitters bootstrap警报消息。 在我的application.html.erb我有……

 <div class="alert alert-"> ×  

通常当我想做一个flash消息时,我会写一些类似的东西

 flash[:success] = "Profile updated" 

但我不知道如何给设计错误消息一个键和值对。 我查看了devise.en.yml,但似乎无法将消息与密钥相关联,即:成功,:错误等可能有人帮忙吗? 谢谢!

我就是这样做的

 <% flash.each do |key, value| %> 
&times
<%= value %>
<% end %>

对于遇到这种情况的人来说,不知道如何使用bootstrap覆盖设计错误消息。

  1. 创建名为的文件:

/app/helpers/devise_helper.rb

  1. 添加以下代码:
 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 

#{sentence}

#{messages}
HTML html.html_safe end end

我发现最简单的解决方案是在检查以下内容时对所有flash消息使用公共部分:notice:alert以替换必需的bootstrap类。

所以像这样制作/views/shared/_alerts.html.erb

 <% flash.each do |message_type, message| %> 
<%= message %>
<% end %>

添加一个帮助方法(我已将它添加到应用程序助手中),如下所示 –

 def flash_class_name(name) case name when "notice" then "success" when "alert" then "danger" else name end end 

在应用程序布局中包含_alerts.html.erb (或应用程序的父布局)。

而已!

事情是devise_error_messages! 单独使用class='alert'将数据包装到div中,因此表单将具有2个具有相同类的嵌套div。 按下x按钮将关闭嵌套的div,将空div设置为alert 。 为避免这种情况,您可以省略辅助返回值中的div,如下所示:

 module DeviseHelper def devise_error_messages! return '' if resource.errors.empty? messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join html = <<-HTML  #{messages} HTML html.html_safe end end