Search code examples
ruby-on-railsrubyruby-on-rails-3

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.


Solution

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