8

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

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How does one go about determining the false return of create when it's throwing exceptions? Does one have to handle the exception merely to find out that validation failed?
not entirely correct, .create can throw ActiveRecord::RecordNotUnique if you have a unique index and no validation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.