How to implement a singleton model

后端 未结 13 1431
余生分开走
余生分开走 2020-12-24 12:36

I have a site in rails and want to have site-wide settings. One part of my app can notify the admin by SMS if a specific event happens. This is an example of a feature that

13条回答
  •  长情又很酷
    2020-12-24 12:38

    I will put a few remarks to the previous answers:

    • no need for a separate field for uniq index, we can put the constraint on the id field. Since we should have id field in a Rails app anyway, it's a good tradeoff
    • no need special validations on the model and explicit ID assignment, it's enough to put default value on the column

    If we apply these modifications, the solution becomes very easy:

    # migration
    create_table :settings, id: false do |t|
      t.integer :id, null: false, primary_key: true, default: 1, index: {unique: true}
      t.integer :setting1
      t.integer :setting2
      ...
    end
    
    # model
    class Settings < ApplicationRecord
      def self.instance
        first_or_create!(...)
      end  
    end
    

提交回复
热议问题