Reputation: 1535
I just started learning ROR. And came across this DOUBT.
I have defined multiple databases in my database.yml file like this:
development:
adapter: mysql2
encoding: utf8
reconnect: true
database: mydb1
username: root
password: root
host: localhost
custom:
adapter: mysql2
encoding: utf8
reconnect: true
database: customdb
username: root
password: root
host: localhost
Now if I create a model using rails generate model MyModel
, it will generate a migration to create table - my_models
in mydb1
.
My question is "How can I create/specify a model, that to create a table under customdb?"
Do I need to change my rails environment or is there any other way? I am just curious. I can do this manually by creating a table in customdb
and creating a model without migration.
Upvotes: 0
Views: 424
Reputation: 1191
I think it's not a matter of environment.
This is my pattern. In few words I created an abstract model, (between AR and your other-db models, where I specify this fact. All models derived from it point to the other db (public_database in my gist). Connections parameters are stored in an extra .yml file (config/database_public.yml)
Running rake tasks on multiple databases is harder but, in the second part of the gist, I found a way to create tasks which operate on both databases but separately.
Upvotes: 0
Reputation: 45
I can't understand why you would like to generate model for specific db.
All you have to do is generate standart model and add this line establish_connection :custom
to it. This model should work with your custom db, you can run migrations as usual after adding establish_connection
.
Upvotes: 0
Reputation: 1468
You would need to specify environment in rails g command, then It will create a table automatically in customdb database
RAILS_ENV=custom rails generate model MyModel
Upvotes: 2