Skip to content

Instantly share code, notes, and snippets.

@namelessjon
Created February 19, 2012 11:02
Show Gist options
  • Save namelessjon/1863177 to your computer and use it in GitHub Desktop.
Save namelessjon/1863177 to your computer and use it in GitHub Desktop.
Gist showing nested/self-referential model
class Folder
include DataMapper::Resource
has n, :subfolders, 'Folder'
has n, :messages
belongs_to :parent, :model => 'Folder', :required => false
belongs_to :owner, :model => 'User', :key => true
property :id, String, :key => true
property :name, String
property :special, String
end
#!/usr/bin/env ruby
#
# Not quite as elegant, but brute force seems to work.
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
# setup the logger
DataMapper::Logger.new($stdout, :debug)
# connect to the DB
DataMapper.setup(:default, 'sqlite3::memory:')
class User
include DataMapper::Resource
has n, :folders, :child_key => [:owner_address]
property :address, String, :key => true, :required => true
property :name, String
end
class Folder
include DataMapper::Resource
property :id, String, :key => true
property :name, String
property :special, String
property :owner_address, String, :key => true, :required => true
has n, :subfolders, 'Folder', :child_key => [:parent_id, :owner_address]
belongs_to :parent, 'Folder', :required => false, :child_key => [:parent_id, :owner_address]
belongs_to :owner, 'User', :key => true, :child_key => [:owner_address]
end
DataMapper.finalize.auto_migrate!
u = User.create(:address => 'a@b.c')
f = Folder.create(:id => 'test', :owner => u)
sf = Folder.create(:id => 'example', :owner => u, :parent => f)
__END__
~ (0.000102) SELECT sqlite_version(*)
~ (0.000234) DROP TABLE IF EXISTS "users"
~ (0.000053) PRAGMA table_info("users")
~ (0.000435) CREATE TABLE "users" ("address" VARCHAR(50) NOT NULL, "name" VARCHAR(50), PRIMARY KEY("address"))
~ (0.000076) DROP TABLE IF EXISTS "folders"
~ (0.000041) PRAGMA table_info("folders")
~ (0.000309) CREATE TABLE "folders" ("id" VARCHAR(50) NOT NULL, "name" VARCHAR(50), "special" VARCHAR(50), "owner_address" VARCHAR(50) NOT NULL, "parent_id" VARCHAR(50), PRIMARY KEY("id", "owner_address"))
~ (0.000127) CREATE INDEX "index_folders_parent" ON "folders" ("parent_id")
~ (0.000102) INSERT INTO "users" ("address") VALUES ('a@b.c')
~ (0.000119) INSERT INTO "folders" ("id", "owner_address") VALUES ('test', 'a@b.c')
~ (0.000125) INSERT INTO "folders" ("id", "owner_address", "parent_id") VALUES ('example', 'a@b.c', 'test')
class User
include DataMapper::Resource
belongs_to :domain
has n, :folders
has n, :messages, :through => :folders
property :address, String, :key => true, :required => true
property :password, BCryptHash, :required => true
property :name, String
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment