简体   繁体   English

Rails连接到远程数据库

[英]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 当我写connect_to_remote_db似乎没问题

I know that remote db has table 'Team' 我知道远程数据库具有表'Team'

but when i write Team in console it returns me uninitialized constant Team 但是当我在控制台中编写Team ,它会返回未初始化的常量团队

How to handle it properly? 如何正确处理?

When you call Team ActiveRecord's primary connection is looked up, hence the error. 当您致电Team ActiveRecord时,将查找主要连接,因此会出现错误。

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. 由于我已经处理过类似的情况,因此可以在database.yml本身中使用该连接并使用。

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 来自-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 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: 使用database.yml文件存储连接:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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