简体   繁体   中英

Understanding ruby on rails 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,

  • 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM