5

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

Shiva
  • 11,485
  • 2
  • 67
  • 84
Ganesh Kunwar
  • 2,643
  • 2
  • 20
  • 36

3 Answers3

3

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

rails g active_record:model Animal name:string
Community
  • 1
  • 1
pmoreira
  • 171
  • 1
  • 1
  • 8
1

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.

Chris Bailey
  • 4,126
  • 24
  • 28
0

So the quick and dirty way that I have handled this in the past (due to my dev team keeping mongoid in the gem file for legacy reasons) is to comment out the out mongoid when you have to do migrations run a bundle, generate and run you migration then uncomment and run bundle again. This is far from best practices but it should work.

C dot StrifeVII
  • 1,885
  • 1
  • 16
  • 21