У меня есть что-то вроде следующего кода.(Названия моделей изменились, поскольку они не важны для происходящего.)
#find_or_create_bar_for_blah_id в большинстве случаев работает нормально.Однако иногда он возвращает ноль, и я не уверен, почему.
Это какое-то состояние гонки, так как проблема возникает в заданиях Resque, которые выполняются как часть нашего приложения.
Любые подсказки каккак #find_or_create_bar_for_blah_id может вернуть ноль?
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"