Skip to content

Instantly share code, notes, and snippets.

@thejbsmith
Last active April 16, 2024 00:29
Show Gist options
  • Save thejbsmith/21380b3181c7b6a2b9f9 to your computer and use it in GitHub Desktop.
Save thejbsmith/21380b3181c7b6a2b9f9 to your computer and use it in GitHub Desktop.
Rails Singleton Model
class CreateSettings < ActiveRecord::Migration
def change
create_table :settings do |t|
t.integer :singleton_guard
t.string :setting_1
t.integer :setting_2
t.timestamps null: false
end
add_index(:settings, :singleton_guard, :unique => true)
end
end
Rails Singleton Model
Taken from:
http://stackoverflow.com/questions/399447/how-to-implement-a-singleton-model/12463209#12463209
class Settings < ActiveRecord::Base
# The "singleton_guard" column is a unique column which must always be set to '0'
# This ensures that only one AppSettings row is created
validates :singleton_guard, inclusion: { in: [0] }
def self.instance
# there will be only one row, and its ID must be '1'
begin
find(1)
rescue ActiveRecord::RecordNotFound
# slight race condition here, but it will only happen once
row = Settings.new
row.singleton_guard = 0
row.save!
row
end
end
def self.method_missing(method, *args)
if Settings.instance.methods.include?(method)
Settings.instance.send(method, *args)
else
super
end
end
# Validations
end
@pjmartorell
Copy link

I don't think it's a good idea to hardcode id 1 in find(1) because ids are created sequentially, probably it would be better to use first_or_create.

@pjmartorell
Copy link

pjmartorell commented Aug 18, 2020

Now I see it was implemented for an older version of Rails, so makes sense not to use first_or_create

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment