Skip to content

Instantly share code, notes, and snippets.

@namelessjon
Created June 10, 2012 10:20
Show Gist options
  • Save namelessjon/2904835 to your computer and use it in GitHub Desktop.
Save namelessjon/2904835 to your computer and use it in GitHub Desktop.
Example of friendships and retriving all records.
#!/usr/bin/env ruby
#
# Example of friendships and retriving all records.
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 Person
include DataMapper::Resource
property :id, Serial
property :name , String, :required => true
def all_friends
self.class.all('friendships.source_id' => self.id) | self.class.all('friendships.target_id' => self.id)
end
has n, :friendships, :child_key => [ :source_id ]
has n, :friends, self, :through => :friendships, :via => :target
end
class Friendship
include DataMapper::Resource
belongs_to :source, 'Person', :key => true
belongs_to :target, 'Person', :key => true
end
DataMapper.finalize.auto_migrate!
@alice = Person.create(:name => 'Alice')
@bob = Person.create(:name => 'Bob')
@charlotte = Person.create(:name => 'Charlotte')
@david = Person.create(:name => 'David')
@eve = Person.create(:name => 'Eve')
@alice.friends << @bob
@alice.save
p @alice.friends
p @bob.friends
p @bob.all_friends
@charlotte.friends << @david
@charlotte.save
@eve.friends << @david
@eve.save
@david.friends << @bob
@david.save
p @david.all_friends
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment