重构ActiveRecord模型有一个基类与基本模块 [英] Refactoring ActiveRecord models with a base class versus a base module

查看:146
本文介绍了重构ActiveRecord模型有一个基类与基本模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A类和B是相同的:

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

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

什么是重构之间的区别是这样一个基类

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

class A < Base
end

class B < Base
end

与像这样使用基本模块

module Base
 def foo
  puts "foo"
 end
end

class A < ActiveRecord::Base
 include Base
end

class B < ActiveRecord::Base
 include Base
end

是一种方式preferable对另一?

推荐答案

还有其他所有的答案都缺少这两种方法之间的根本区别,那就是Rails的实施性传播感染的(单表继承):

There's a fundamental difference between those two methods that all the other answers are missing, and that's rails' implementation of STIs (Single Table Inheritance):

<一个href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html">http://api.rubyonrails.org/classes/ActiveRecord/Base.html (找到单表继承一节)

http://api.rubyonrails.org/classes/ActiveRecord/Base.html (Find the "Single Table Inheritance" section)

基本上,如果你重构你的基类是这样的:

Basically, if you refactor your Base class like this:

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

class A < Base
end

class B < Base
end

那么,你应该有一个名为基地一个数据库表中,有一个名为类型一栏,里面应该有A或B的值。该表中的列将在所有的车型一样,如果你有一个只属于一个模型的一列,你的基地表将非规范化。

Then, you are supposed to have a database table called "bases", with a column called "type", which should have a value of "A" or "B". The columns on this table will be the same across all your models, and if you have a column that belongs to only one of the models, your "bases" table will be denormalized.

然而,如果你重构你的基类是这样的:

Whereas, if you refactor your Base class like this:

Module Base
  def foo
  puts "foo"
 end
end

class A < ActiveRecord::Base
 include Base
end

class B < ActiveRecord::Base
 include Base
end

然后就没有表基地。相反,会出现一个表作为和表BS。如果它们具有相同的属性,该列将在这两个表中复制,但如果有差异,他们不会被denomarlized

Then there will be no table "bases". Instead, there will be a table "as" and a table "bs". If they have the same attributes, the columns will have to be duplicated across both tables, but if there are differences, they won't be denomarlized.

因此​​,如果一个是preferable比其他,是的,但这是特定于应用程序。作为一个经验法则,如果他们有相同的属性或一个大的重叠,使用STI(第一例子),否则,使用模块(第二个示例)。

So, if one is preferable over the other, yes, but that's specific to your application. As a rule of thumb, if they have the exact same properties or a big overlap, use STI (1st example), else, use Modules (2nd example).

这篇关于重构ActiveRecord模型有一个基类与基本模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆