Last active
April 16, 2024 00:29
-
-
Save thejbsmith/21380b3181c7b6a2b9f9 to your computer and use it in GitHub Desktop.
Rails Singleton Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails Singleton Model | |
Taken from: | |
http://stackoverflow.com/questions/399447/how-to-implement-a-singleton-model/12463209#12463209 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
I don't think it's a good idea to hardcode
id
1
infind(1)
because ids are created sequentially, probably it would be better to usefirst_or_create
.