1

I am currently creating a rails application.
I am writing a model and wants to add some validation.
from the documentation I see that doing something like this works

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: { message: 'must be abided' }
end

I am trying to understand the validates method here.
At a more general level I would like to understand rails documentation better.
My understanding is that validates is a class method of ApplicationRecord::Base. It is possible to reuse it with various parameters and options. The best doc I found is this.
I do not understand where I can find a list of all validates options and parameters.
In this case,

  • what is acceptance?
  • where can I find a description of it in the doc?
  • where can I find a list of all other possible validates parameters?

Any tips on how to understand ruby on rails documentation better would be appreciated.

1 Answer 1

1
validates :terms_of_service, acceptance: true

acceptance maps to AcceptanceValidator which is a default rails validator:

https://github.com/rails/rails/blob/main/activemodel/lib/active_model/validations/acceptance.rb

All of the default validators are listed in the example:

https://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates

absence
acceptance
confirmation
exclusion
format
inclusion
length
numericality
presence

and additional validators that are added by ActiveRecord:

associated
uniqueness

https://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

Available options for each validaror are documented in the helper methods here:

https://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html

validates :terms_of_service, acceptance: true
# is the same as using a helper method
validates_acceptance_of :terms_of_service
# and both map to rails default `AcceptanceValidator`

You can have custom validators as well:

validates :terms_of_service, terms: true # maps to `TermsValidator`

# because there is no TermsValidator class in rails, you have to define it
# class TermsValidator
# # TODO: see docs for examples of custom validators
# end

https://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations

Sign up to request clarification or add additional context in comments.

Comments

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.