Rails extending ActiveRecord::Base

后端 未结 9 1637
眼角桃花
眼角桃花 2020-11-22 12:38

I\'ve done some reading about how to extend ActiveRecord:Base class so my models would have some special methods. What is the easy way to extend it (step by step tutorial)?<

9条回答
  •  攒了一身酷
    2020-11-22 13:13

    With Rails 5, all models are inherited from ApplicationRecord & it gives nice way to include or extend other extension libraries.

    # app/models/concerns/special_methods.rb
    module SpecialMethods
      extend ActiveSupport::Concern
    
      scope :this_month, -> { 
        where("date_trunc('month',created_at) = date_trunc('month',now())")
      }
    
      def foo
        # Code
      end
    end
    

    Suppose the special methods module needs to be available across all models, include it in application_record.rb file. If we wants to apply this for a particular set of models, then include it in the respective model classes.

    # app/models/application_record.rb
    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
      include SpecialMethods
    end
    
    # app/models/user.rb
    class User < ApplicationRecord
      include SpecialMethods
    
      # Code
    end
    

    If you want to have the methods defined in the module as class methods, extend the module to ApplicationRecord.

    # app/models/application_record.rb
    class ApplicationRecord < ActiveRecord::Base
      self.abstract_class = true
      extend SpecialMethods
    end
    

    Hope it help others !

提交回复
热议问题