Model With Self-referential Association
Join the DZone community and get the full member experience.Join For Free
class Chunk < ActiveRecord::Base has_many :separations, :foreign_key => 'composite_id', :class_name => 'Composition', :order => "id", :dependent => :destroy has_many :components, :through => :separations has_many :sequences, :foreign_key => 'component_id', :class_name => 'Composition', :dependent => :destroy has_many :composites, :through => :sequences end class Composition < ActiveRecord::Base belongs_to :composite, :class_name => "Chunk" belongs_to :component, :class_name => "Chunk" end:foreign_key -- refers to that chunk which has_many compositions (:separations or :sequences) :class_name => 'Composition' -- is necessary because we need 2 different names for the compostition according to, where they lead to. :dependent => :destroy -- on compositions because compositions connect two chunks (composite and one of its components) and they make sense only when both chunks exist. :order => "id" -- on separations maintains the order (if they are created in the same order in which the according components appear in the componsite) See also: http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through
Opinions expressed by DZone contributors are their own.