Dan
Dan

Reputation: 2319

Validate Boolean True of an Association

I have a model Assignment which belongs_to model Device

before an Assignment row gets created I need to validate that a boolean value for the corresponding device is set to true otherwise the creation should fail. How can this be done?

Upvotes: 3

Views: 721

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34328

You can use Rails custom validation to validate your Assignment model based on it's Device's boolean_attribute.

In your Assignment Model, add this custom validator:

validate :true_device_attribute

Then, define the validator method in the same Model:

 def true_device_attribute
    unless device.boolean_attribute
      errors.add(:boolean_attribute, "Device's boolean_attribute Must be True")
    end
 end

By default, such validations will run every time you call valid?.

You can also control when to run your custom validator. If you only want to perform the validation while creating the assignment, then you can pass :on :create option to the validate method like this:

validate :true_device_attribute, on: :create

Then the validation will only run when you try to create Assignment records. Not for update. By default, it will work for both create and update.

Look at the Rails Official Documentation for Validations Custom Methods for more insights.

Upvotes: 1

un_gars_la_cour
un_gars_la_cour

Reputation: 269

class Assignment < ...

validate :check_device_boolean_value

def check_device_boolean_value
  errors.add(:your_boolean_value, "must to boolean") unless devise.your_boolean_value
end

Upvotes: 1

Related Questions