Customized Many To Many Relationship With DataMapper
Join the DZone community and get the full member experience.Join For Free
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.chunk_id.should == chunk_1.id chunk_1.occurrences.context_id.should == context_1.id chunk_1.occurrences.name.should == 'test' chunk_1.contexts.should == context_1 chunk_1.contexts.should == context_2 chunk_2.contexts.should == context_1 context_1.chunks.should == chunk_1 context_1.chunks.should == chunk_2 context_2.chunks.should == chunk_1 end end
Relational database DataMapper
Opinions expressed by DZone contributors are their own.