I've found plenty of posts around how to validate a field is present, if another condition is true, such as these:
Rails: How to validate format only if value is present?
Rails - Validation :if one condition is true
However, how do I do it the opposite way around?
My User has an attribute called terms_of_service.
How do I best write a validation that checks that the terms_of_service == true, if present?
You're looking for the acceptance validation.
You can either use it like this:
class Person < ApplicationRecord
validates :terms_of_service, acceptance: true
end
or with further options, like this:
class Person < ApplicationRecord
validates :terms_of_service, acceptance: { message: 'must be abided' }
end
[edit]
You can set the options you expect the field to be as well, as a single item or an array. So if you store the field inside a hidden attribute, you can check that it is still "accepted" however you describe accepted:
class Person < ApplicationRecord
validates :terms_of_service, acceptance: { accept: ['yes', 'TRUE'] }
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With