yellowreign
yellowreign

Reputation: 3638

Rails Validate Field is True, If Present

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?

Upvotes: 2

Views: 5511

Answers (2)

philnash
philnash

Reputation: 73100

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

Upvotes: 5

Pavan
Pavan

Reputation: 33552

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

Upvotes: 1

Related Questions