3

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?

6
  • What is the datatype of terms_of_service? boolean? Commented Jun 21, 2017 at 5:14
  • Yes, it's a boolean. Commented Jun 21, 2017 at 5:16
  • To check it its true or to validate that it should be true? Commented Jun 21, 2017 at 5:20
  • I want to check that the value is true (they agreed to the terms) when the form is submitted. Commented Jun 21, 2017 at 5:21
  • And to add error if its not true, right? Commented Jun 21, 2017 at 5:23

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I think this would normally work, but this field will be hidden (not a checkbox).
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".
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

1 Comment

"a boolean can be either truthy or falsy" No, booleans are either true or false. Eg 1 is truthy but booleans cannot evaluate to 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.