Refactoring ActiveRecord models with a base class versus a base module

前端 未结 5 1311
执念已碎
执念已碎 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:00

    The module gives you more flexibility in that 1) you can only inherit from one class, but you can include multiple modules, and 2) you can't inherit from a base class without inheriting its superclasses, but you can include a module all by itself (e.g. you might want to add the "foo" method to another class that isn't an active record model).

    Another difference is that within the methods in the class Base you could call things from ActiveRecord::Base, but you couldn't do that from the module.

提交回复
热议问题