Apply pattern to make `find_or_create` atomic

This commit is contained in:
Gabriel Mazetto 2018-07-23 23:06:35 +02:00
parent 2d85ad23c0
commit 32d96d482d
1 changed files with 10 additions and 7 deletions

View File

@ -25,18 +25,21 @@ class SiteStatistic < ActiveRecord::Base
return unless available?
# we have quite a lot of specs testing migrations, we need this and the rescue to not break them
SiteStatistic.transaction(requires_new: true) do
SiteStatistic.first_or_create
self.fetch # make sure record exists
attribute = self.connection.quote_column_name(raw_attribute)
# will be running on its own transaction context
yield(attribute)
end
end
def self.fetch
SiteStatistic.transaction(requires_new: true) do
SiteStatistic.first_or_create!
end
rescue ActiveRecord::RecordNotUnique
retry
end
def self.available?
@available_flag ||= ActiveRecord::Migrator.current_version >= REQUIRED_SCHEMA_VERSION