Rails - Validate on Create Only

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?


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


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!