首先在application_helper.rb文件下加入下面两个方法
#error_messages_for方法修改 def error_messages_for(*params) options = params.last.is_a?(Hash) ? params.pop.symbolize_keys : {} objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact error_messages = objects.map do |object| sort_show_error_msg(object) end count = objects.inject(0) {|sum, object| sum + error_messages[0].size} unless count.zero? html = {} [:id, :class].each do |key| if options.include?(key) value = options[key] html[key] = value unless value.blank? else html[key] = 'errorExplanation' end end error_message = "個の入力の不備が" header_message = "#{count} #{error_message} あります。" # Change 'error' to 'errors' for english setups void of a localization plugin header_message.gsub!("error", "errors") if header_message.include?(error_message) and count > 1 content_tag(:div, content_tag(options[:header_tag] || :h2, header_message) << content_tag(:p, 'There were problems with the following fields:') << content_tag(:ul, error_messages), html ) else '' end end def sort_show_error_msg(obj) # config = active_scaffold_config msg_arr = obj.errors.sort #去除隐藏字段 hidden_attr = obj.class::HIDDEN_ATTRIBUTES rescue [] msg_arr.delete_if{|key,val|hidden_attr.include?(key)} unless hidden_attr.blank? #排序 hash_field_orders = obj.class::HUMANIZED_ATTRIBUTES_ORDERS rescue [] unless hash_field_orders.blank? msg_arr = msg_arr.sort do |key_a,key_b| hash_field_orders[key_a[0].to_sym] hash_field_orders[key_a[0].to_sym] <=> hash_field_orders[key_b[0].to_sym] end end full_messages = [] msg_arr.each do|attr,msg| next if msg.nil? if attr == "base" full_messages << msg else label = obj.class.human_attribute_name(attr) full_messages << content_tag(:li,"#{label + " " + msg}") end end return full_messages end
然后在你想要排序model里加入
HUMANIZED_ATTRIBUTES_ORDERS = { :login=> 1, :name => 2, :email => 3, :password => 4, :password_confirmation => 5 }
后面的数字就是错误信息的位置
然后view中写:
<%= error_messages_for :user %>