2011-04-04 83 views
0

我有一個數據模型,我想在Rails中描述它。有許多Entity,每個has_many :blobs,和每個Blobbelongs_to一個Entity。此外,每個Entity可能belong_to父母Entity。它應該繼承父母的所有Blobs。有沒有在Rails中建模的好方法?換句話說,有沒有辦法做這樣的事情:Rails中的「繼承」數據

# Beware, wrong code 
class Entity < ActiveRecord::Base 
    has_many :blobs 
    has_many :blobs, :through => :parent, :source => :blobs 
end 

或者也許有關如何做到這一點不同的想法?

回答

1

的東西非常相似,這應該工作:

class Entity 
    belongs_to :parent, :class_name => 'Entity', :foreign_key => 'parent_id' 
    has_many :children, :class_name => 'Entity', :foreign_key => 'parent_id' 
    has_many :direct_blobs, :class_name => 'Blob' 
    has_many :inherited_blobs, :class_name => 'Blob', :through => :parent, :source => :direct_blobs 

    def blobs 
    direct_blobs + inherited_blobs 
    end 
end 
+0

很好的解決方案,謝謝。 – 2011-04-05 11:45:48