微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Mysql2 ::错误:密钥的重复条目 – ActiveRecord :: RecordNotUnique没有捕获错误?

我正在使用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…

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐