2011-04-04 84 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