2011-07-22 171 views
1

假設我有一個人員表,我希望它將所有人分類爲alpha或omegas。所有的omegas都有一個alpha,但沒有omegas,所有的alpha都有任何數量的omegas,但沒有alpha。ActiveRecord和兩級層次結構

這是一個簡單的兩個層次結構,這點我可以編碼使用一個外鍵:

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 

它會是不錯的關閉拆分人變成兩個子類,一個是阿爾法,一個用於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

使用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得到你所尋找的對象。這有幫助嗎?