Efficient way to pull data from second database?

前端 未结 3 896
隐瞒了意图╮
隐瞒了意图╮ 2021-01-06 14:41

We have a primary database where all of our app resides.

But there\'s a second database (updated from an external source), that I\'d like to be able to connect to so

3条回答
  •  走了就别回头了
    2021-01-06 15:32

    Copy/Paste:

    For a single-master situation, you could define another database connection in database.yml for the read slave:

    read_slave:
      adapter: postgresql
      database: read_only_production
      username: user
      password: pass
      host: read_slave_host
    

    This database is backed by a module, which mirrors the ActiveRecord classes using this database connection:

    require 'magic_multi_connections'
    module ReadSlave
      establish_connection :read_slave
    end
    

    Now, all pre-existing models can be accessed through the read_slave connection by prefixing the model class with ReadSlave::.

    # use the read-only connection
        @user = ReadSlave::User.find(params[:id])
    
        # write to the master (can't use @user.update_attributes because it would#
        try to write to the read slave)
        User.update(@user.id, :login => "new_login")
    

提交回复
热议问题