How to implement a singleton model

后端 未结 13 1376
余生分开走
余生分开走 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:48

    Simple:

    class AppSettings < ActiveRecord::Base 
      before_create do
        self.errors.add(:base, "already one setting object existing") and return false if AppSettings.exists?      
      end
    
      def self.instance
        AppSettings.first_or_create!(...) 
      end 
    end
    

提交回复
热议问题