Home > Enterprise >  Rails validation integer value grater then if other field value
Rails validation integer value grater then if other field value

Time:09-03

I want to check an integer value in validation. But I want to do it depending on the value of another field. For example, if the width value exists, let it be at least 300 if the width_type is "px", but 30 if the width_type is "rate". How can I do it thanks.

CodePudding user response:

If I understand correctly you are looking for conditional validation

In that case the following should work:

validates :width, numericality: { only_integer: true}
validates :width, numericality: { greater_than_or_equal_to: 300}, if: -> {width_type.to_s == 'px'}
validates :width, numericality: { greater_than_or_equal_to: 30}, if: -> {width_type.to_s == 'rate'}

If you need to handle too many other scenarios I would go with a custom validation like

MIN_WIDTH_PER_TYPE = {px: 300, rate: 30} 

validates :width, numericality: { only_integer: true}
validate :_width_with_type 


private
def _width_with_type 
  min_width = MIN_WIDTH_PER_TYPE[width_type.to_sym]
  if width < min_width
    errors.add(:width, "must be at least #{min_width} when using width type '#{width_type}'") 
  end
end 

You could clean this up further as well but this should point you in the right direction.

  • Related