ActiveRecord和两级层次结构

时间:2011-07-22 18:27:59

标签: ruby activerecord subclassing

假设我有一张人桌,我希望它将所有人归类为alphas或omegas。所有omegas都有一个alpha但没有omegas,所有alphas都有任意数量的omegas但没有alpha。

这是一个简单的两级层次结构,我可以使用单个外键进行编码:

CREATE TABLE people (
  id INTEGER NOT NULL PRIMARY KEY,
  alpha_id INTEGER FOREIGN KEY REFERENCES people, 
  -- alpha_id is NULL if and only if this person is an alpha
  -- other stuff we know about people...
);

现在我可以创建一个普通人类,但是当我达到alpha-omega关系时,它会有点尴尬。

class Person < ActiveRecord::Base
  # ... stuff I know about people

  # if alpha_id is NULL
    has_many :omegas, :as => :alpha, :class_name => Person
  # else 
    belongs_to :alpha, :class_name => Person
end

很高兴将这个人分成两个子类,一个用于Alphas,一个用于Omegas,但我不确定它与ActiveRecord的效果如何。

理想情况下,我喜欢这样的事情:

class Person < ActiveRecord::Base
  # ... stuff I know about people
end
class Alpha < Subset(Person)
  column_is_null :alpha_id
  has_many :omegas
end
class Omega < Subset(Person)
  column_is_not_null :alpha_id
  belongs_to :alpha
end

ActiveRecord中是否提供了这种子类化或近似它的东西?

1 个答案:

答案 0 :(得分:1)

使用 named_scope

 class Person < ActiveRecord::Base
   # ... stuff I know about people
   named_scope :alphas, :conditions => { :alpha_id => nil }
   named_scope :omegas, :conditions => "alpha_id IS NOT NULL"

   # if alpha_id is NULL
   has_many :omegas, :as => :alpha, :class_name => Person
   # else 
   belongs_to :alpha, :class_name => Person
 end

现在您可以参考 Person.alphas Person.omegas 来获取您要查找的对象。这有帮助吗?