Christoffer Christoffer - 1 year ago 107
Ruby Question

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)?

Answer Source

Use a lambda/proc in the :if condition:

validates_numericality_of ...., 
  if: -> record { record.bmi_calculation? && record.is_metric? }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download