Mysql::Error: Duplicate entry

≯℡__Kan透↙ 提交于 2019-12-22 17:51:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!