Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 770
oprogfrogo Avatar asked May 25 '12 01:05

oprogfrogo


People also ask

How does validation work in Rails?

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.

What is Active Record in Ruby on Rails?

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.

What is Validates_presence_of?

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.


1 Answers

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

like image 176
Tonys Avatar answered Oct 13 '22 18:10

Tonys