Rails - Validate on Create Only

Ruby on-Rails

Ruby on-Rails Problem Overview


I'm trying to get my custom validation to work on create. But when I do a find then save, rails treats it as create and runs the custom validation. How do I get the validations to only work when creating a new record on not on the update of a found record?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try this on your line of validation code:

validate :custom_validation, on: :create

this specifies to only run the validation on the create action.

Source:

ActiveModel/Validations/ClassMethods/validate @ apidock.com

Solution 2 - Ruby on-Rails

TL;DR; Full example:
class MyPerson < ActiveRecord::Base
  validate :age_requirement


  private

  def age_requirement
    unless self.age > 21 
      errors.add(:age, "must be at least 10 characters in length")
    end
  end

end

To have the validator run only if a new object is being created, you can change the 2nd line of the example to: validate :age_requirement, on: :create

Only on updates: validate :age_requirement, on: :update

Hope that helps the next person!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionoprogfrogoView Question on Stackoverflow
Solution 1 - Ruby on-RailsTonysView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMattView Answer on Stackoverflow