简体   繁体   中英

Rails connect to remote db

How to properly connect to remote db?

Now i have

  def db_params
    {:adapter => "mysql2",
     :host => "host",
     :username => "name",
     :password => "pass",
     :database => "mydb"}
  end



 def connect_to_remote_db
    ActiveRecord::Base.establish_connection(db_params)
  end

When i write connect_to_remote_db it seems ok

I know that remote db has table 'Team'

but when i write Team in console it returns me uninitialized constant Team

How to handle it properly?

When you call Team ActiveRecord's primary connection is looked up, hence the error.

You could probably wrap that in class.

Since I had dealt with similar situation, you could have that connection in database.yml itself and use.

development:
  adapter: mysql2
  other stuff...

db_2:
  adapter: mysql2
  other stuff..

Then create a class

class Team < ActiveRecord::Base
  establish_connection(:db_2)
  self.table_name = "teams"
end

from - https://stackoverflow.com/a/26574386/2231236

You need to create model in your application ( of that remote db table) and establish connection. Example:

team.rb

class Team< ActiveRecord::Base
  establish_connection "remote_db"
end

If you have multiple table you want to use from that remote db, you can make module and just include it in every model for remote db table. Module example:

module RemoteConnection
  extend ActiveSupport::Concern
  included do
    establish_connection "remote_db"
  end
end

and than

class Team< ActiveRecord::Base
  include RemoteConnection
end

Use database.yml file to store connections:

...
remote_db:
  :adapter => "mysql2",
  :host => "host",
  :username => "name",
  :password => "pass",
  :database => "mydb"
...

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