简体   繁体   中英

Multiple database schemas in Rails 3 and MySQL

Is there any to specify a different schema for an ActiveRecord model in Rails 3? The following used to work in Rails 2:

class Company < ActiveRecord::Base
  set_table_name "hr.company"
end

This fails in Rails 3 with the message Table myapp.hr.company doesn't exist .

The following works for simple models:

class Company < ActiveRecord::Base
  establish_connection "hr"
  set_table_name "company"
end

The problem with this approach is twofold: first, Rails creates a separate database connection for this model, imposing an additional overhead. Second, all queries are now invoked in the context of this connection, meaning that any joins back to the myapp schema will break:

class Company < ActiveRecord::Base
  establish_connection "hr"
  set_table_name "company"
  has_many :widgets # widgets table resides in myapp schema
end

This in turn will fail with Table hr.widgets doesn't exist .

So, is there any way to achieve this in Rails 3?

You can use abstract class and inherit from it:

app/models/db.rb

class Db < ActiveRecord::Base
  establish_connection :db
  self.abstract_class = true
end

app/models/post.rb

class Post < Db
  set_table_name :notes
  belongs_to :user
end

app/models/user.rb

class User < ActiveRecord::Base
  has_many :posts
end

config/database.yml

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000


db:
  adapter: sqlite3
  database: db/db.sqlite3
  pool: 5
  timeout: 5000

In db.sqlite3 there is only notes table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM