BLAX_21
BLAX_21

Reputation: 13

Understanding ruby on rails validations documentation

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,

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

Upvotes: 1

Views: 104

Answers (1)

Alex
Alex

Reputation: 29766

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

Upvotes: 1

Related Questions