How can i make ruby on rails handle duplicate record errors from MySQL How can i make ruby on rails handle duplicate record errors from MySQL ruby ruby

How can i make ruby on rails handle duplicate record errors from MySQL


begin  Event.create!(:name => 'Ironman Lanzarote 2011')rescue ActiveRecord::RecordNotUnique => e  # handle duplicate entry end

This works for me under Rails 3.


You can add a uniqueness constraint to your model so that the record returns with errors and is invalid.

For example (Rails 2):

class User < ActiveRecord::Base  validates_uniqueness_of :email, :scope => [:name, :age]end

or (Rails 3)

class User < ActiveRecord::Base  validates :email, :uniqueness => {:scope => [:name, :age]}end

This should result in the following:

user1 = User.create :email => "one@example.com", :name => "one", :age => 20user2 = User.create :email => "one@example.com", :name => "one", :age => 20user2.valid? # false


Can you change the query to

INSERT IGNORE INTO `entries` ...

Alternatively, you could consider INSERT... ON DUPLICATE KEY UPDATE....

The INSERT Documentation is here.