Back to Blog

Rails 5 accepts 1 or true for acceptance validation

on May 13, 2016
This blog is part of our Rails 5 series.

validates_acceptance_of is a good validation tool for asking users to accept "terms of service" or similar items.

Before Rails 5, the only acceptable value for a validates_acceptance_of validation was 1.

1
2class User < ActiveRecord::Base
3  validates_acceptance_of :terms_of_service
4end
5
6> user = User.new(terms_of_service: "1")
7> user.valid?
8#=> true
9

Having acceptable value of 1 does cause some ambiguity because general purpose of acceptance validation is for attributes that hold boolean values.

So in order to have true as acceptance value we had to pass accept option to validates_acceptance_of as shown below.

1
2class User < ActiveRecord::Base
3  validates_acceptance_of :terms_of_service, accept: true
4end
5
6> user = User.new(terms_of_service: true)
7> user.valid?
8#=> true
9
10> user.terms_of_service = '1'
11> user.valid?
12#=> false
13

Now this comes with the cost that 1 is no longer an acceptable value.

In Rails 5, we have true as a default value for acceptance along with the already existing acceptable value of 1.

In Rails 5 the previous example would look like as shown below.

1
2class User < ActiveRecord::Base
3  validates_acceptance_of :terms_of_service
4end
5
6> user = User.new(terms_of_service: true)
7> user.valid?
8#=> true
9
10> user.terms_of_service = '1'
11> user.valid?
12#=> true
13

Rails 5 allows user to have custom set of acceptable values

In Rails 5, :accept option of validates_acceptance_of method supports an array of values unlike a single value that we had before.

So in our example if we are to validate our terms_of_service attribute with any of true, "y", "yes" we could have our validation as follows.

1
2class User < ActiveRecord::Base
3  validates_acceptance_of :terms_of_service, accept: [true, "y", "yes"]
4end
5
6> user = User.new(terms_of_service: true)
7> user.valid?
8#=> true
9
10> user.terms_of_service = 'y'
11> user.valid?
12#=> true
13
14> user.terms_of_service = 'yes'
15> user.valid?
16#=> true
17

You might also like

If you liked this blog post, check out similar ones from BigBinary