Rails custom validation contexts

In rails, it is possible to specify when the validation should happen. sometimes you may want to introduce new validation or skip some. Rails on option helps us achieve this.

class Post < ApplicationRecord
validates :body, presence: true
valida…


This content originally appeared on DEV Community and was authored by Moses Gathuku

In rails, it is possible to specify when the validation should happen. sometimes you may want to introduce new validation or skip some. Rails on option helps us achieve this.

class Post < ApplicationRecord
 validates :body, presence: true
 validates :title, uniqueness: true, on: :create 
 validates :published, exclusion: [nil], on: :update 
end

From the above validations:

  • it's not possible to create or update a post without a body
  • it will be possible to update a post with a duplicate title
  • it will be possible to create a record with published nil

Apart from the commonly used on: :create and on: :update rails allow us to provide custom contexts.

class Post < ApplicationRecord
 validates :title, presence: true 
 validates :published_at, presence: true, on: :publish
end

From the above example, we are validating published_at presence on: :publish. Custom contexts are triggered explicitly by passing the name of the context to valid? invalid? or save

post = Post.new(title: "Rails validations")
post.valid? # true 
post.valid?(context: :publish) # false 
post.save(context: :publish) # false


This content originally appeared on DEV Community and was authored by Moses Gathuku


Print Share Comment Cite Upload Translate Updates
APA

Moses Gathuku | Sciencx (2022-04-24T19:53:30+00:00) Rails custom validation contexts. Retrieved from https://www.scien.cx/2022/04/24/rails-custom-validation-contexts/

MLA
" » Rails custom validation contexts." Moses Gathuku | Sciencx - Sunday April 24, 2022, https://www.scien.cx/2022/04/24/rails-custom-validation-contexts/
HARVARD
Moses Gathuku | Sciencx Sunday April 24, 2022 » Rails custom validation contexts., viewed ,<https://www.scien.cx/2022/04/24/rails-custom-validation-contexts/>
VANCOUVER
Moses Gathuku | Sciencx - » Rails custom validation contexts. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/04/24/rails-custom-validation-contexts/
CHICAGO
" » Rails custom validation contexts." Moses Gathuku | Sciencx - Accessed . https://www.scien.cx/2022/04/24/rails-custom-validation-contexts/
IEEE
" » Rails custom validation contexts." Moses Gathuku | Sciencx [Online]. Available: https://www.scien.cx/2022/04/24/rails-custom-validation-contexts/. [Accessed: ]
rf:citation
» Rails custom validation contexts | Moses Gathuku | Sciencx | https://www.scien.cx/2022/04/24/rails-custom-validation-contexts/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.