
-----------------------------------
DtY
Mon Jun 29, 2009 11:10 am

DataMapper: Hierarchy System
-----------------------------------
What I am trying to achieve is a hierarchy of categories. What it needs to do is have categories, each with an optional parent, and optional children. Then, have an easy way to get all the categories that don't have a parent (top level categories), as well as get all the children of a category (which wouldn't be trouble at all).

What I was thinking was making a special category called top level or something, which would be it's own parent (like the object class in Ruby), and then everything in there would be a subcategory of that. Is that the best method?

So something like this:
class Category
    include DataMapper::Resource
    property :id,   Serial
    property :name, String
    
    has 1, :parent #Not sure on how to make is have a Category, but not accessed through .category
    has n, :children #Same thing here
end

-----------------------------------
DtY
Mon Jun 29, 2009 3:15 pm

RE:DataMapper: Hierarchy System
-----------------------------------
Okay, I got it figured out. Apparently one to many relationships can be empty, so top level categories have the parent nil.

require 'rubygems'
require 'dm-core'
require 'dm-validations'
require 'dm-timestamps'
require 'dm-types'

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/db.sqlite3")

class Category
    include DataMapper::Resource
    property :id,   Serial
    property :name, String
    
    #Hierarchy
    belongs_to :parent, :class_name=>'Category', :child_key=>

-----------------------------------
gianni
Tue Jul 14, 2009 4:52 pm

RE:DataMapper: Hierarchy System
-----------------------------------
Isn't DataMapper awesome?

-----------------------------------
DtY
Sat Jul 18, 2009 9:44 am

RE:DataMapper: Hierarchy System
-----------------------------------
So much!
