I have a model that represents an assembly that is made up of components, components may (in their own right) also be assemblies. It looks a little like this:
class Component < ActiveRecord::Base
belongs_to :assembly, :class_name => "Component", :foreign_key => :assembly_id
has_many :pieces, :class_name => "Component", :foreign_key => :assembly_id
end
I want to be certain that when I add a component to the assembly that what's being added isn't the assembly itself, or another assembly up the chain. Effectively, an assembly can't contain itself, regardless of how many levels down you go.
My thought is to traverse the tree going up when a component is saved to look for the component itself as a parent, grandparent, etc. I'm trying to avoid circular references.
Is there an "easy, Rails-ish" way to do this? Any other suggestions?