20

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

1
  • 1
    It also doesn't treat them as OR. The second :if overrides the first one. Commented Dec 13, 2019 at 10:04

1 Answer 1

53

Use a lambda as the if condition:

validates_numericality_of :person_weight_kg, 
  if: -> record { record.bmi_calculation? && record.is_metric? }
Sign up to request clarification or add additional context in comments.

3 Comments

It doesn't work in Rails 5. Do you have any solution?
maybe because it should declare the parameter inside the lambda block if: -> { |record| record.bmi_calculation? && record.is_metric? }
Update for 2024: if: proc{ |record| record.bmi_calculation? && record.is_metric? }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.