Nested transaction for find_or_create_by! queries.
For background see https://apidock.com/rails/v4.2.7/ActiveRecord/Relation/find_or_create_by.
This commit is contained in:
parent
e83e85ce11
commit
d270b85734
1 changed files with 11 additions and 5 deletions
|
@ -23,11 +23,17 @@ class UserInteractedProject < ActiveRecord::Base
|
||||||
}
|
}
|
||||||
|
|
||||||
cached_exists?(attributes) do
|
cached_exists?(attributes) do
|
||||||
begin
|
transaction(requires_new: true) do
|
||||||
find_or_create_by!(attributes)
|
begin
|
||||||
true # not caching the whole record here for now
|
where(attributes).select(1).first || create!(attributes)
|
||||||
rescue ActiveRecord::RecordNotUnique
|
true # not caching the whole record here for now
|
||||||
retry
|
rescue ActiveRecord::RecordNotUnique
|
||||||
|
# Note, above queries are not atomic and prone
|
||||||
|
# to race conditions (similar like #find_or_create!).
|
||||||
|
# We retry and make sure the outer transaction (if any)
|
||||||
|
# is not aborted because of this.
|
||||||
|
retry
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue