2

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?

yellowreign
  • 3,528
  • 8
  • 43
  • 80

2 Answers2

5

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
philnash
  • 70,667
  • 10
  • 60
  • 88
  • I think this would normally work, but this field will be hidden (not a checkbox). – yellowreign Jun 21 '17 at 05:29
  • Updated my answer to include the way you can set the expectation of the field. That way, if it is stored in a hidden attribute, you can choose the answer you want to be "accepted". – philnash Jun 21 '17 at 05:32
1

I can't think of any default validation methods that could serve your purpose, but you can do with a custom validation. Also, a boolean can be either truthy or falsy, so you just need to check if its true or not. something like this should work.

validate :terms_of_service_value

def terms_of_service_value
  if terms_of_service != true
    errors.add(:terms_of_service, "Should be selected/True")
  end
end
Pavan
  • 33,316
  • 7
  • 50
  • 76