In my model I have this:
validates :name, :presence => true, :uniqueness => true
In my controller I have:
...
if @location.save
format.html { redirect_to @location, :notice => 'Location was successfully created.' }
format.json { render :json => @location, :status => :created }
...
which successfully creates a record if there isn't already a record with this name in the table. I think it's good practice to check before inserting a possibly duplicate record instead of relying on the DB constraints?
I guess I should add something to the controller to check? What's the correct way to do this?
Many thanks.
Import Wizard can automatically prevent duplicate records.
Validations are done by Rails before the record would hit the database. If the record fails a validation, it won't save, and .save
will return false
, which will cause the else
clause of your controller to execute. That clause usually rerenders the page that was submitted, with the errors displayed so they can be corrected.
Assuming that your controller is built like that, you don't need to do anything else. You should, naturally, make sure that any database constraints are mirrored in your validations, otherwise a record might pass validations but produce an error from violating a constraint when it was saved.
Add a unique index in your database. That way, if something slips through the model validations (rare, but technically possible), the query to save to the database will fail.
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