Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Create (not !) Throwing Exception on Validation

So I'm using ActiveRecord model validations to validate a form in a RESTful application.

I have a create action that does:

@association = Association.new

and the receiving end of the form creates a data hash of attributes from the form parameters to save to the database using:

@association = user.associations.create(data)

I want to simply render the create action if validation fails. The problem is that the .create (not !) method is throwing an exception in cases where the model validation fails. Example:

validates_format_of :url,         :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix, :message => "Your url doesn't seem valid."

in the model produces:

ActiveRecord::RecordInvalid Exception: Validation failed: Url Your url doesn't seem valid.

I thought .create! is supposed throw an exception whereas .create is not.

Am I missing something here?

Ruby 1.8.7 patchlevel 173 & rails 2.3.3

like image 204
onyxrev Avatar asked Jun 14 '10 03:06

onyxrev


1 Answers

Read the documentation of create and create! carefully.

Both create and create! check the callbacks (in your case validations). create method return false if exception is raised and true if not while, create! method raised exception if the record is invalid.

However, create can throw an ActiveRecord::RecordNotUnique if you have a unique index in the database and no validation set on the model. In this case, you should add validates :fieldname, uniqueness: true onto the model.

like image 183
Salil Avatar answered Sep 21 '22 13:09

Salil