views:

72

answers:

1

Hi

I have a model

class Gift < ActiveRecord::Base
  validates_uniqueness_of :giver_id, :scope => :account_id
end

add_index(:gifts, [:account_id, :giver_id], :uniq => true)

Action

def create
  @gift= Gift.new(params[:gift])

  if @gift.save
    ...
  else
    ...
  end
end

In the "production" mode, I sometimes get an error

ActiveRecord::StatementInvalid: Mysql::Error: Duplicate entry '122394471958-50301499' for key 'index_gifts_on_account_id_and_giver_id'

What the problem?

+1  A: 

Your is made of two values :account_id and :giver_id. If you say :unique => true on your index that means that you are expecting the combination of :account_id and :giver_id to yield a unique value which will be inserted into the index.

Mike Williamson