DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Customized Many To Many Relationship With DataMapper

05.23.2011
| 3683 views |
  • submit to reddit
        Customized many to many relationship with datamapper

require 'rspec'

require 'dm-core'
require 'dm-migrations'
DataMapper.setup(:default, 'sqlite::memory:')


class Chunk 
  include DataMapper::Resource
    
  property :id,           Serial    # auto-increment integer key  
  
  has n, :occurrences
  has n, :contexts,       :through => :occurrences
end


class Context 
  include DataMapper::Resource
  
  property :id,           Serial    # auto-increment integer key
  property :filename,     String    # Context may represent a text-file
  
  has n, :occurrences
  has n, :chunks,         :through => :occurrences
end

# customized relationship (default was ChunkContext)
class Occurrence
  include DataMapper::Resource
  
  property :name,     String, :default => 'test'    # extra property
  
  belongs_to :chunk,   :key => true  # => 'chunk_id'
  belongs_to :context, :key => true  # => 'context_id'
end


DataMapper.finalize.auto_migrate!

describe Occurrence do
  
  it 'chunk has and belongs_to many contexts' do
    context_1 = Context.create
    context_2 = Context.create
    chunk_1 = Chunk.create
    chunk_2 = Chunk.create
    
    chunk_1.contexts << context_1
    chunk_1.contexts << context_2
    chunk_2.contexts << context_1
    chunk_1.save
    chunk_2.save
    
    chunk_1.occurrences[0].chunk_id.should == chunk_1.id
    chunk_1.occurrences[0].context_id.should == context_1.id
    chunk_1.occurrences[0].name.should == 'test'
    
    chunk_1.contexts[0].should == context_1
    chunk_1.contexts[1].should == context_2
    chunk_2.contexts[0].should == context_1
    context_1.chunks[0].should == chunk_1
    context_1.chunks[1].should == chunk_2
    context_2.chunks[0].should == chunk_1
  end
end