Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails with two different Databases

I have used two different databases for my Rails application: MongoDB and MsSQL using Mongoid and activerecord-sqlserver-adapter adapter respectively. Everything is well but there is a problem while generate Model.

The problem is "how can I generate the model that relates to MongoDB or MsSQL differently?"

For example: I want to generate People model relates to MongoID and Animal model with MsSQL. While I generate with command: rails g model Animal name:string it generates the model related to mongoid. How can I generate the model Animal with ActiveRecord that means related to MsSQL.
Please help me. Thanks

like image 792
Ganesh Kunwar Avatar asked Oct 03 '22 19:10

Ganesh Kunwar


2 Answers

Based on Using Active Record generators after Mongoid installation? I believe this should work:

rails g active_record:model Animal name:string
like image 100
pmoreira Avatar answered Oct 11 '22 15:10

pmoreira


First let me just check that I've understood your question correctly:

You have 2 databases and a series of models/migrations, and you want a way to tell rails which database to use when running a migration and accessing the database using your model?

If I'm in the right area then you need to add a method to your migration which overrides the default connection() method in ActiveRecord::Migration.

def connection
  ActiveRecord::Base.establish_connection(:conn_name).connection
end

Where :conn_name is the name you gave your connection settings in config/database.yml

within your models add the line

establish_connection :conn_name

to the top of your model file and the model will now know which DB to connect to.

like image 27
Chris Bailey Avatar answered Oct 11 '22 13:10

Chris Bailey