Friday, June 6, 2008

DataMapper: Parent / Child Relationship

I couldn't find an example at datamapper.org /docs for a parent child relationship.


After a little searching, I found the answer in the integration tests.  Here is the example:

class Node
include DataMapper::Resource

def self.default_repository_name
ADAPTER
end

property :id, Integer, :serial => true
property :name, String

has n, :children, :class_name => 'Node', :child_key => [ :parent_id ]
belongs_to :parent, :class_name => 'Node', :child_key => [ :parent_id ]

end

Hope that helps someone else.

6 comments:

H.J.M. Langenberg said...

It looks more like a tree relationship then a parent/child relationship.

Justin Pease said...

"In a hierarchical data model, data is organized into a tree-like structure. The structure allows repeating information using parent/child relationships: each parent can have many children but each child only has one parent."

http://en.wikipedia.org/wiki/Hierarchical_model

scott said...

This is very helpful, though I'm not too familiar with datamapper. I'm trying to see if it'll fit what I need.

Could this be expanded to the parent becomes,
has n, :children, :class_name => 'Node', :child_key => [:child_id]
has n, :parents, :class_name => 'Node', :child_key => [:parent_id ]

Something like that would work with activerecord, but, like I said I'm not too familiar.

Cheers

Justin Pease said...

scott,

Actually I believe the syntax you suggested is what I first tried, and did not work, and caused the searching.

DataMapper is still somewhat young, so check the integration tests referenced in the post for the most recent developments.

scott said...

Ah, I figured it out.

I didn't write a spec for it, nor would it stop any nonsensical inbred relationships, but:

pastie.

Ian said...

Why not just use the dm-is-tree plugin?

http://github.com/datamapper/dm-more/tree/master/dm-is-tree