MySQL的::错误:重复项 [英] Mysql::Error: Duplicate entry

查看:95
本文介绍了MySQL的::错误:重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型

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

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

动作

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'

什么问题?

推荐答案

它看起来像礼品表有一个唯一索引 ACCOUNT_ID USER_ID

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

编辑:  尝试添加presence检查 giver_id

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

这篇关于MySQL的::错误:重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆