JVK
JVK

Reputation: 3912

How Ruby Datamapper can use different data storage in same app

I am using sinatra with datamapper and have more than one database, that I want to connect to and use them per my logic in the same app.

I have my datamapper settings defined in a file, say app.rb

#Default database
dm = DataMapper.setup :default, {
:adapter => 'mysql',
:path => 'dsfsdf',
:username => 'sdf2r',
:password => '234wer',
:host => 'f3rwefwe'
}

#Logrecord database
lrdm = DataMapper.setup :logrecdm, {
:adapter => 'mysql',
:path => 'dsf34',
:username => 't4h6',
:password => '56erg',
:host => 'g45gfg'
}

#my database
mdb = DataMapper.setup :mydb, {
:adapter => 'mysql',
:path => 'dsf34',
:username => 't4h6',
:password => '56erg',
:host => 'g45gfg'
}

# Here I include all my model files.

DataMapper.finalize

My first model file (xyz_db.rb), that is corresponding to xyz table and this table is located in default data-store :default

    class xyz  
      include DataMapper::Resource  
      property :id, Serial
      property :created_at, DateTime  
    end

My second model file (userlogrecord_db.rb), that is corresponding to userlogrecords table and that table is located in other data-store :logrecdm

class userlogrecord  
  include DataMapper::Resource  
  property :id, Serial  
  property :content, Text, :required => true
  property :created_at, DateTime  
  property :updated_at, DateTime  
end  

My third model file (abc_db.rb), that is corresponding to abc and that table is located in other data-store :mydb

class abc
  include DataMapper::Resource
  is :reflective
  reflect 
end

When I run my app.rb , first model (xyz_db.rb) by default uses default data-store. But for second and third models, I want they should be generated in :logrecdm and :mydb data store respectively. What changes I should make in my second and third model to achieve that? In third data-store (:mydb) I am using dm-reflective. I have looked at http://datamapper.org/docs/misc.html but that does not really help. Any help will be appreciated.

Upvotes: 2

Views: 738

Answers (1)

JVK
JVK

Reputation: 3912

I found the solution

class abc
  include DataMapper::Resource
  def self.default_repository_name
    :mydb
  end

  is :reflective
  reflect 
end

I took the idea from http://workswithruby.com/2008/12/using-datamapper-on-legacy-databases I wish datamapper documentation would have mentioned about it somewhere.

Upvotes: 3

Related Questions