Refactoring ActiveRecord models with a base class versus a base module

前端 未结 5 1327
执念已碎
执念已碎 2021-02-04 08:22

Class A and B are identical:

class A < ActiveRecord::Base
 def foo
  puts \"foo\"
 end
end

class B < ActiveRecord::Base
 def foo
  puts \"foo\"
 end
end
<         


        
5条回答
  •  终归单人心
    2021-02-04 09:18

    It depends on what you are really trying to do.

    1. Overriding or adding methods to ActiveRecord::Base: Do this if you want every ActiveRecord model in your app to respond_to foo.
    2. Subclass ActiveRecord::Base, and have every model inherit from your subclass: Achieves the same as 1, but every model in your app needs to extend an unconventional class, so why go through the trouble.
    3. include module: This works great if only some number of models need access to foo. This is pretty much what all those acts_as_ plugins do.

    Bottom line, if you want every single model to have a different behavior to what ActiveRecord::Base already provides, use option 1. If only a handful of your models require the behavior, create a module and include it in your models (option 3).

提交回复
热议问题