加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Mysql2 ::错误:密钥的重复条目 – ActiveReco

发布时间:2020-12-17 02:45:00 所属栏目:百科 来源:网络整理
导读:我正在使用rails应用程序,并且经常遇到以下错误: Mysql2::Error: Duplicate entry '3022093-2000000028003-visited' for key 'unique_user_place_relationship' 虽然我已将问题的根源缩小到以下几行: begin up = UserPlace.new(user_place_params) up.skip
我正在使用rails应用程序,并且经常遇到以下错误:

Mysql2::Error: Duplicate entry '3022093-2000000028003-visited' for key 'unique_user_place_relationship'

虽然我已将问题的根源缩小到以下几行:

begin
  up = UserPlace.new(user_place_params)
  up.skip_logging
  up.save!
rescue ActiveRecord::RecordNotUnique => e
  Rails.logger.warn(e)
end

在我的表中,我有以下索引:

key_name                         seq_in_index    column_name
unique_user_place_relationship   1               user_id
unique_user_place_relationship   2               place_id
unique_user_place_relationship   3               relationship

问题是我的user_place.rb中没有validate_uniqueness_of user_id,place_id和relationship吗?

根据我的理解,ActiveRecord:RecordNotUnique应该捕获此错误,因为事务不满足db级别的索引约束.

解决方法

doc说:

Using this validation method in conjunction with
ActiveRecord::Validations#save does not guarantee the absence of
duplicate record insertions,because uniqueness checks on the application level are inherently prone to race conditions. For example,suppose that two users try to post a Comment at the same time,and a Comment’s title must be unique. At the database-level,the actions performed by these users could be interleaved in the following manner…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读