1

我有類似下面的代碼。 (型號名稱已更改,因爲它們對於發生的事情並不重要。)獲取ActiveRecord :: RecordNotUnique,但無法找到現有記錄

大多數情況下#find_or_create_bar_for_blah_id都能正常工作。偶爾它會返回零,但我不知道爲什麼。

這是某種競爭條件,因爲問題發生在作爲我們應用程序的一部分運行的resque作業中。

任何關於#find_or_create_bar_for_blah_id可能返回nil的線索?

class Foo < ActiveRecord::Base 
    has_many :bars, :dependent => :destroy 

    def find_or_create_bar_for_blah_id(locale_id) 
    begin 
     bars.where(:blah_id => blah_id).first || bars.create!(:blah_id => blah_id) 
    rescue ActiveRecord::RecordNotUnique 
     bars.where(:blah_id => blah_id).first 
    end 
    end 
end 

class Bar < ActiveRecord::Base 
    belongs_to :foo 
    validates_uniqueness_of :blah_id, :scope => :foo_id 
end 


# db/schema.rb 

create_table "bars", :force => true do |t| 
    t.integer "foo_id" 
    t.integer "blah_id" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

add_index "bars", ["foo_id", "blah_id"], :name => "index_bars_on_foo_id_and_blah_id", :unique => true 
add_index "bars", ["foo_id"], :name => "index_bars_on_foo_id" 

create_table "foos", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

add_index "foos", ["name"], :name => "index_foos_on_name" 

回答

1

Doh!這是因爲我們在部分代碼中使用了update_attribute,這當然不會運行AR驗證。 尷尬的臉

相關問題