Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of prevent duplicate records in Rails

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.

like image 417
ale Avatar asked May 24 '13 12:05

ale


People also ask

Which of the following prevents duplication of records?

Import Wizard can automatically prevent duplicate records.


2 Answers

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.

like image 184
MrTheWalrus Avatar answered Sep 27 '22 22:09

MrTheWalrus


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.

like image 25
Teddy Avatar answered Sep 27 '22 23:09

Teddy