Rails extending ActiveRecord::Base

后端 未结 9 1496
眼角桃花
眼角桃花 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:19

    You can just extend the class and simply use inheritance.

    class AbstractModel < ActiveRecord::Base  
      self.abstract_class = true
    end
    
    class Foo < AbstractModel
    end
    
    class Bar < AbstractModel
    end
    
    0 讨论(0)
  • 2020-11-22 13:21

    I have

    ActiveRecord::Base.extend Foo::Bar
    

    in an initializer

    For a module like below

    module Foo
      module Bar
      end
    end
    
    0 讨论(0)
  • 2020-11-22 13:24

    You can also use ActiveSupport::Concern and be more Rails core idiomatic like:

    module MyExtension
      extend ActiveSupport::Concern
    
      def foo
      end
    
      module ClassMethods
        def bar
        end
      end
    end
    
    ActiveRecord::Base.send(:include, MyExtension)
    

    [Edit] following the comment from @daniel

    Then all your models will have the method foo included as an instance method and the methods in ClassMethods included as class methods. E.g. on a FooBar < ActiveRecord::Base you will have: FooBar.bar and FooBar#foo

    http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

    0 讨论(0)
提交回复
热议问题