Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Multiple if conditions in validation

Using: Rails 3.0.3

I have validations such as this one:

  validates_numericality_of :person_weight_kg, :greater_than => 0, :message => "value_must_be_number_over_zero", :if => :bmi_calculation?, :if => :is_metric?   

That I would like to validate for multiple if-conditions (such as in the example). But it seems, however, that Rails treats these statements as OR. One returns false and one returns true which makes the validation go through.

So, how do I check that this validation fulfills BOTH if-statements (bmi_calculation AND is_metric)?

like image 895
Christoffer Avatar asked Oct 04 '11 10:10

Christoffer


1 Answers

Use a lambda as the if condition:

validates_numericality_of :person_weight_kg, 
  if: -> record { record.bmi_calculation? && record.is_metric? }
like image 164
tokland Avatar answered Sep 30 '22 05:09

tokland