2013-03-06 82 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