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
Based on Using Active Record generators after Mongoid installation? I believe this should work:
rails g active_record:model Animal name:string
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With