问题
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_user_id'
What the problem?
回答1:
It looks like the gifts table has an unique index for account_id and user_id.
Add an uniqueness check to your model if you need this index:
class Gift < ActiveRecord::Base
validates_uniqueness_of :giver_id, :scope => :account_id
validates_uniqueness_of :user_id, :scope => :account_id
end
Otherwise drop the index.
DROP INDEX index_gifts_on_account_id_and_user_id ON gifts
Edit:
Try adding a presence check for giver_id.
class Gift < ActiveRecord::Base
validates_presence_of :giver_id
validates_uniqueness_of :user_id, :scope => :account_id
end
来源:https://stackoverflow.com/questions/2605625/mysqlerror-duplicate-entry