views:

19

answers:

1

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  A: 

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.

Salil
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?
myferalprofessor