Rails validation error messages: Displaying only one error message per field

后端 未结 13 887
情话喂你
情话喂你 2020-12-07 17:08

Rails displays all validation error messages associated with a given field. If I have three validates_XXXXX_of :email, and I leave the field blank, I get three

13条回答
  •  死守一世寂寞
    2020-12-07 18:02

    I use this code for Ruby on Rails 3.0 release, which I put in lib/core_ext/rails/active_model/errors.rb:

    module ActiveModel
      class Errors
        def full_message_per_field
          messages_per_field = []
          handled_attributes = []
    
          each do |attribute, messages|
            next if handled_attributes.include? attribute
            messages = Array.wrap(messages)
            next if messages.empty?
    
            if attribute == :base
              messages_per_field << messages.first
            else
              attr_name = attribute.to_s.gsub('.', '_').humanize
              attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
              options = { :default => "%{attribute} %{message}", :attribute => attr_name }
    
              messages_per_field << I18n.t(:"errors.format", options.merge(:message => messages.first))
            end
    
            handled_attributes << attribute
          end
    
          messages_per_field
        end
      end
    end
    

    This is essentially the same code as ActiveModel::Errors#full_messages, but won't show more than one error per attribute. Be sure to require the file (say, in an initializer) and now you can call @model.errors.full_message_per_field do |message| ...

提交回复
热议问题