Commit 32d96d48 authored by Gabriel Mazetto's avatar Gabriel Mazetto

Apply pattern to make `find_or_create` atomic

parent 2d85ad23
...@@ -25,18 +25,21 @@ class SiteStatistic < ActiveRecord::Base ...@@ -25,18 +25,21 @@ 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) attribute = self.connection.quote_column_name(raw_attribute)
# will be running on its own transaction context
yield(attribute) yield(attribute)
end end
end
def self.fetch def self.fetch
SiteStatistic.transaction(requires_new: true) do
SiteStatistic.first_or_create! SiteStatistic.first_or_create!
end end
rescue ActiveRecord::RecordNotUnique
retry
end
def self.available? def self.available?
@available_flag ||= ActiveRecord::Migrator.current_version >= REQUIRED_SCHEMA_VERSION @available_flag ||= ActiveRecord::Migrator.current_version >= REQUIRED_SCHEMA_VERSION
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment