0

I want to add a validation in my model where I have 2 fields:

t.boolean :first
t.boolean :second

I want to ensure that when

first field is false

then

second field is always false

Is that possible?

3 Answers 3

2

You can do something like this in Rails3:

class MyValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless {your condition here}
      object.errors[attribute] << (options[:message] || "your error here") 
    end
  end
end

Edit: Forgot to mention that this example is from Railscasts: http://railscasts.com/episodes/211-validations-in-rails-3 in case you need more detailed information on this topic

Sign up to request clarification or add additional context in comments.

2 Comments

What is the advantage of using a new class instead of a method like all the others suggested?
Class is reusable and more readable, other solutions will lead to copy-paste (eventually).
2
validate :if_first_is_false_second_is_also
def if_first_is_false_second_is_also
  if self.first_field == false && self.second_field != false
    errors.add(:second_field, "your error message")
  end
end

More on validations

Comments

1

I assume here that when first is true, it's always ok.

validate :check_booleans

def check_booleans
  if first == false
     errors[:base] << "wrong here" if second == true
  end
end

1 Comment

Validations do not check return values, you need to add errors to the object: self.errors.add(:second, "can't be false")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.