How to configure error messages to check subparameters of numerical values?

How to configure error messages for auxiliary parameters when checking the numerical value of a field in the ActiveRecord model?

Example:

validates :month, :numericality => {
  :greater_than_or_equal_to => 1,
  :less_than_or_equal_to    => 12
}

In this case, if the "month" attribute is greater than 12, I want to provide a custom error message instead of the default value "must be less than or equal to 12". How to achieve this?

+5
source share
2 answers

, en.yml. , "post" - , , - ( ) .

en:
  activerecord:
    errors:
      models:
        post:
          attributes:
            age:
              less_than_or_equal_to: "Age-specific error" # Applies only to post.age
          less_than_or_equal_to: "Post-specific error" # Applies to all other fields for a post
      messages:
        less_than_or_equal_to: "Generic error" # Applies to all other models
+8

, :

validates_numericality_of :month, 
    greater_than_or_equal_to: 1,
    less_than_or_equal_to: 12,
    message: "My custom error message"

:

validates_numericality_of :month, 
    greater_than_or_equal_to: 1,
    message: "Too small"

validates_numericality_of :month, 
    less_than_or_equal_to: 12,
    message: "Too big
0

All Articles