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?
Before saving an Active Record object, Rails runs your validations. If these validations produce any errors, Rails does not save the object. After Active Record has performed validations, any errors found can be accessed through the errors instance method, which returns a collection of errors.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
validates_presence_of(*attr_names) public. Validates that the specified attributes are not blank (as defined by Object#blank?), and, if the attribute is an association, that the associated object is not marked for destruction. Happens by default on save.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With