Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 DataMapper: Hierarchy System
Index -> Programming, Ruby -> Ruby Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
DtY




PostPosted: Mon Jun 29, 2009 11:10 am   Post subject: 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:
Ruby:
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
Sponsor
Sponsor
Sponsor
sponsor
DtY




PostPosted: Mon Jun 29, 2009 3:15 pm   Post subject: 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.

Ruby:
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=>[:parent_key]
    has n, :children, :class_name=>'Category'
end
def Category.topLevels
    all :parent_key=>nil
end

DataMapper.auto_upgrade!
gianni




PostPosted: Tue Jul 14, 2009 4:52 pm   Post subject: RE:DataMapper: Hierarchy System

Isn't DataMapper awesome?
DtY




PostPosted: Sat Jul 18, 2009 9:44 am   Post subject: RE:DataMapper: Hierarchy System

So much!
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: