2011-07-22 10 views
1

私は人テーブルを持っていて、アルファまたはオメガのようにすべての人を分類したいとしましょう。すべてのオメガには正確に1つのアルファがありますが、オメガはありません。すべてのアルファは任意の数のオメガを持ちますが、アルファはありません。ActiveRecordと2レベルの階層

これは私が単一の外部キーを使用してエンコードすることができ、単純な2つのレベルの階層、次のとおりです。

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... 
); 

は、今私は、一般的な人のクラスを作成することができますが、私はアルファを取得するとき、それは少しぎこちない取得オメガ関係。

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 

2つのサブクラス、アルファに1つ、オメガのために一つに人を切り離すのはいいだろうが、私はそれは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

使用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.alphasPerson.omegasを参照することができます。これは役に立ちますか?

関連する問題