Skip to content

Instantly share code, notes, and snippets.

@g3d
Last active December 14, 2015 03:09
Show Gist options
  • Save g3d/5019043 to your computer and use it in GitHub Desktop.
Save g3d/5019043 to your computer and use it in GitHub Desktop.
self referential m:m relationships
class Category
include DataMapper::Resource
property :id, Serial
# some other properties here
has n, :user_children, 'Categoryship', child_key: [ :source_id ]
has n, :user_parents, 'Categoryship', child_key: [ :target_id ]
has n, :children, self, through: :user_children, via: :target
has n, :parent, self, through: :user_parents, via: :source
end
class Categoryship
include DataMapper::Resource
belongs_to :source, 'Category', key: true
belongs_to :target, 'Category', key: true
end
[4] pry(main)> Model::Category.first(main: true).children
=> []
[5] pry(main)> Model::Category.first(main: true).parent
=> [#<Model::Category @id=3 @name=<not loaded> @slug=<not loaded> @main=false @created_at=#<DateTime: 2013-02-23T11:32:40+00:00 ((2456347j,41560s,0n),+0s,2299161j)> @created_on=#<Date: 2013-02-23 ((2456347j,0s,0n),+0s,2299161j)> @updated_at=#<DateTime: 2013-02-23T11:35:36+02:00 ((2456347j,34536s,0n),+7200s,2299161j)> @updated_on=#<Date: 2013-02-23 ((2456347j,0s,0n),+0s,2299161j)>>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment