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
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.
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