glarkou
glarkou

Reputation: 7101

Database model validation

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?

Upvotes: 0

Views: 82

Answers (3)

Ransom Briggs
Ransom Briggs

Reputation: 3095

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

Upvotes: 2

Zepplock
Zepplock

Reputation: 29175

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

Upvotes: 2

apneadiving
apneadiving

Reputation: 115541

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

Upvotes: 1

Related Questions