1
다음 코드와 같은 것이 있습니다. (모델 이름은 변경 사항이 중요하지 않으므로 변경되었습니다.)ActiveRecord 얻기 :: RecordNotUnique 그러나 기존 레코드를 찾을 수 없습니다.
#find_or_create_bar_for_blah_id는 대부분 잘 작동합니다. 때때로 그것은 nil을 반환 할 것이고 나는 왜 확신하지 못합니다.
문제는 응용 프로그램의 일부로 실행되는 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"