• error_messages_for错误信息排序


    首先在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 %>
  • 相关阅读:
    终端等级UE Category—4G数据传输流程系列(五)
    4G数据传输流程系列(四)—物理层OFDM、MIMO实现
    4G数据传输流程系列(三)—物理层“从传输块到码字”
    4G网络数据传输流程与速率分析(二)--资源调度
    4G网络数据传输流程与速率分析系列(一)
    G.711 u律;A律 压缩算法
    VLAN IEEE802.1Q
    64B/66B编码
    Operator与优化
    对偶与Proximal
  • 原文地址:https://www.cnblogs.com/mingforyou/p/2799184.html
Copyright © 2020-2023  润新知