Apply pattern to make `find_or_create` atomic
This commit is contained in:
parent
2d85ad23c0
commit
32d96d482d
|
@ -25,17 +25,20 @@ class SiteStatistic < ActiveRecord::Base
|
||||||
|
|
||||||
return unless available?
|
return unless available?
|
||||||
|
|
||||||
# we have quite a lot of specs testing migrations, we need this and the rescue to not break them
|
self.fetch # make sure record exists
|
||||||
SiteStatistic.transaction(requires_new: true) do
|
|
||||||
SiteStatistic.first_or_create
|
|
||||||
attribute = self.connection.quote_column_name(raw_attribute)
|
|
||||||
|
|
||||||
yield(attribute)
|
attribute = self.connection.quote_column_name(raw_attribute)
|
||||||
end
|
|
||||||
|
# will be running on its own transaction context
|
||||||
|
yield(attribute)
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.fetch
|
def self.fetch
|
||||||
SiteStatistic.first_or_create!
|
SiteStatistic.transaction(requires_new: true) do
|
||||||
|
SiteStatistic.first_or_create!
|
||||||
|
end
|
||||||
|
rescue ActiveRecord::RecordNotUnique
|
||||||
|
retry
|
||||||
end
|
end
|
||||||
|
|
||||||
def self.available?
|
def self.available?
|
||||||
|
|
Loading…
Reference in New Issue