rails errors样式自定义

通常rails页面的错误信息提示都是放在首部用 error_message_for,生成这样的错误提示:

image

这样很快就把所有错误信息都显示出来了。但是有一个缺点,就是灵活性太差。感觉error_message_for就像rails的scaffold一样可以快速搭建一个CURD(增删改查)应用,但是定制性不高。
还好,rails的可扩展能力是很强的,你不喜欢里面的某一方法,你甚至可以去把他的源代码改了(当然不推荐这样做...),所以只有自己动手..

看了下源码:

1
2
3
4
    # Returns the Errors object that holds all information about attribute error messages. 
        def errors 
          @errors ||= Errors.new(self
       end
1
  

这一句就够了:原来每个ActiveRecord的实例都有一个errors方法。这个@errors就是所有rails其他错误信息处理封装的基础。
自己写了一个对每个model的field错误信息提取到div的方法,同时把汉化也加进去了,很简单。。

1
2
3
4
5
6
7
8
9
10
11
12
13
module ApplicationHelper 
   def error_div(model, field, field_name) 
     return unless model 
     field = field.is_a?(Symbol) ? field.to_s : field 
     errors = model.errors[field] 
     return unless errors 
     %Q
     <div class="errors"
     #{errors.is_a?(Array) ? errors.map{|e| field_name + e}.join(",") : field_name << errors} 
     </div> 
     
   end 
 end
1
  

demo:
validation:

1
2
3
4
class Post < ActiveRecord::Base 
  validates_presence_of :title, :message => "不能为空" 
  validates_length_of   :title, :in => 2..10, :message => "长度不正确" 
end

view:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<% form_for(@post) do |f| %>  
 
  <p>  
    <%= f.label :title %><br />  
    <%= f.text_field :title %><%= sanitize(error_div(@post, :title, "标题"))%>  
  </p>  
  <p>  
    <%= f.label :description %><br />  
    <%= f.text_area :description %>  
  </p>  
  <p>  
    <%= f.submit 'Create' %>  
  </p>  
<% end %>

效果1:
image
效果2:
image

原文地址:https://www.cnblogs.com/feichan/p/2280002.html