views:

268

answers:

3

I have a trouble trying to get this working. I have an Item model, and each Item can have other items or nothing.

So is this possible or do I need to do some magic?

+2  A: 

You can either use the acts as tree plugin or build it your self:

belongs_to                :parent,
                          :foreign_key => "parent_id",
                          :class_name => "Item"

has_many                  :children,
                          :foreign_key => 'parent_id',
                          :class_name => 'Item',
                          :order => 'created_at ASC',
                          :dependent => :delete_all
vise
AN alternative to a_a_tree is acts_as_nested_set which has much better performance for read operations.
Toby Hede
+1  A: 

Check out self-referential association.

Rich Apodaca
A: 

There's probably some AR builtins or libs plugins / gems to handle most non-bizarre use cases, but: Not clear if you're talking about a

  • join table / Actve record association, (heterogeneous relationsip, 2 or three tables)
  • nested set / acts_as_tree, (tree of like objects in one table) or
  • Single table inheritance, somewhat heterogeneous objects in one table

or, the messiest thing, a - Entity-Attribute-Value table (EAV) design

http://en.wikipedia.org/wiki/Entity-Attribute-Value%5Fmodel

Gene T