Alexander Popov
Alexander Popov

Reputation: 24875

How to generate a model, whose table in stored in a different database?

I work with an app, which uses three different databases. I want to create a model and store its table in one particular database, which is not the default appname_development database. How do I tell the rails generator where to create the DB table for this model?

Upvotes: 1

Views: 54

Answers (2)

Fer
Fer

Reputation: 3347

You can use the establish_connection method.

class SomeClassInDb1 < ActiveRecord::Base
  establish_connection "db_1_#{Rails.env}"
end


class SomeClassInDb2 < ActiveRecord::Base
  establish_connection "db_2_#{Rails.env}"
end

and in your config/database.yml

development:
  # your normal db settings

db_1_development:
  # config for db 1 in development env

db_2_development:
  # config for db 2 in development env

db_1_test:
  # config for db 1 in test env
db_2_test:
  # config for db 2 in test env

db_1_production:
  # config for db 1 in production env

db_2_production:
  # config for db 2 in production env

Upvotes: 0

Shadwell
Shadwell

Reputation: 34774

In short: you can't. You can't tell the model generator which database to use to create the table (out of the box).

You'd need to change the generated migration yourself to target the database you want using establish_connection. Something like:

conn = ActiveRecord::Base.establish_connection(:"which_db_#{Rails.env}")
conn.create_table :my_table do |t|

Instead of the usual call to create_table that gets generated for you.

You'll also need to add the establish_connection call to any models.


However, you could provide your own templates for the the generation of the your migration and model though in order to add those lines for any generated model. There's more details in the generators guide but you should be able to provide versions of the files to generate a model and a migration. You'd then have to react to a variable passed in on the rails generate to specify which db to use. Might be a bit fiddly but probably worth it if you're going to get generating a lot of models in different places.

Upvotes: 1

Related Questions