2013-03-06 87 views
3

我工作的一个Rails应用程序,并已经常收到以下错误:Mysql2 ::错误:键重复项 - ActiveRecord :: RecordNotUnique不捕捉错误?

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 

是这个问题,我没有validate_uniqueness_of USER_ID,PL ace_id和我的关系user_place.rb

从我的理解,ActiveRecord:RecordNotUnique应该捕获此错误,因为事务不符合数据库级别的索引约束。

+2

**是**,你应该有'validates_uniqueness_of'到位**除了**的数据库级约束。 – deefour 2013-03-06 20:20:14

回答

5

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...

2

不太清楚有什么问题,增加validates_uniqueness_of但如果你真的不想使用,你是说,rescue不捕捉异常,请尝试删除ActiveRecord::RecordNotUnique => e一起,看看它是否捕捉异常在这种情况下。

尝试类似如下:

rescue Exception => e 
    if e.is_a? ActiveRecord::RecordNotUnique 
    Rails.logger.warn(e) 
    end