ActiveRecord validates… custom field name

后端 未结 3 1629
别跟我提以往
别跟我提以往 2020-12-21 15:40

I would like to fix up some error messages my site generates. Here is the problem:

class Brand < ActiveRecord::Base
    validates_presence_of :foo
    ...         


        
相关标签:
3条回答
  • 2020-12-21 15:42

    You can do as given below:

    # config/locales/en.yml
    en:
      activerecord:
        attributes:
          brand:
            foo: "Ticket description"
        errors:
          models:
            brand:
              attributes:
                foo:
                  blank: " is required"
    

    Please check Fully custom validation error message with Rails for more details.

    0 讨论(0)
  • 2020-12-21 15:56

    Add this to your config/locales/en.yml file:

    en:
      activerecord:
        errors:
    
          # global message format 
          format: #{message}
    
          full_messages:
            # shared message format across models
            foo:
              blank: Ticket description is required
    
            # model specific message format
            brand:
              zoo:
                blank: Name is required
    

    Now change your validation message to refer to the new message format:

    validates_presence_of :bar, :message => "Empty bar is not a good idea"
    validates_presence_of :foo, :message => "foo.blank"
    validates_presence_of :zoo, :message => "brand.zoo.blank"
    

    Lets try the code:

    b = Brand.new
    b.valid?
    b.errors.full_messages
    #=> ["Ticket description is required", 
    #     "Empty bar is not a good idea",
    #     "Name is required"]
    

    As demonstrated above, you can customize the error message format at three levels.

    1) Globally for all the ActiveRecord error messages

      activerecord:
        errors:
          format: #{message}
    

    2) Shared error messages across models

      activerecord:
        errors:
          full_messages:
            foo:
              blank: Ticket description is required
    

    3) Model specific messages

      activerecord:
        errors:
          full_messages:
            brand:
              zoo:
                blank: Name is required
    
    0 讨论(0)
  • 2020-12-21 16:06

    So the answer was quite simple...

    define

    self.human_attribute_name(attribute) and return the human readable name:

    def self.human_attribute_name(attribute)
        if attribute == :foo 
            return 'bar'
        end
    end
    

    I'd use a map of names of course. And thats that.

    0 讨论(0)
提交回复
热议问题