欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

Connecting to multiple databases in ruby on rails 一个rails连接多个数据库

https://stackoverflow.com/questions/17311199/connecting-to-multiple-databases-in-ruby-on-rails

 

For multiple database connection, you need to add the following codes to the database.yml file. Here, I am giving the example of connecting two databases from a rails application

config/database.yml

development:
  adapter: mysql2
  database: db1_dev
  username: root
  password: xyz
  host: localhost

development_sec:
  adapter: mysql2
  database: db2_dev
  username: root
  password: xyz
  host: localhost

production:
  adapter: mysql2
  database: db1_prod
  username: root
  password: xyz
  host: your-production-ip

production_sec:
  adapter: mysql2
  database: db2_prod
  username: root
  password: xyz
  host: your-production-ip

Here I have used two databases for the development and production environment.

Now we need to connect the model to databases. When you are running your application in development and production mode, all the models will be mapped through the development and production db parameters those been mentioned in your database.yml. So for some model we need to connect to other database.

Lets assume that, we have two models User and Category. The users table is in db1_dev and db1_prod, the categories table in db2_dev and db2_prod.

Category model

class Category < ActiveRecord::Base
  establish_connection "#{Rails.env}_sec"
end

Similarly, when you adding the new migration for the second database, need to add following code to it.

class CreateRewards < ActiveRecord::Migration
  def connection
    ActiveRecord::Base.establish_connection("#{Rails.env}_sec").connection
  end

  def change
    # your code goes here.
  end
end

返回列表