简体   繁体   English

访问模型或表时建立连接

[英]establish_connection when accessing model or table

I'm trying to connect to 2 databases in my Rails application. 我正在尝试连接到我的Rails应用程序中的2个数据库。

I created 2 models in my RoR app which is for 2 tables on 2 different databases. 我在RoR应用程序中创建了2个模型,该模型用于2个不同数据库上的2个表。

I know how to connect to the other database before accessing the table using: 我知道在使用以下方法访问表之前如何连接到另一个数据库:

ActiveRecord::Base.establish_connection() 

But what I'm trying to accomplish is to automatically set the connection to the correct database every time I call on that model/table because I'm required to have different databases. 但是我要完成的工作是,每次我调用该模型/表时,都会自动将连接设置为正确的数据库,因为需要具有不同的数据库。

Just like the before_filter on the Rails controllers, how can I get my rails app to run a method that establishes a connection like this: 就像Rails控制器上的before_filter一样,如何让我的rails应用程序运行一个建立连接的方法,如下所示:

 def set_database 
      ActiveRecord::Base.establish_connection({ :adapter => 'nuodb',:database => 'test_db',:host => 'localhost',:username => 'test_username',:password => 'test_password', :schema  => 'TEST_SCHEMA'})
    end

I would like to run this method everytime I call a model. 我想在每次调用模型时都运行此方法。

I've been looking at ActiveModel::Callbacks but I can't seem to find a callback for this. 我一直在看ActiveModel :: Callbacks,但我似乎找不到此回调。

All your models inherit from ActiveRecord::Base. 您的所有模型都继承自ActiveRecord :: Base。 So establish_connection is available in the model directly. 因此,可以在模型中直接使用Establishment_connection。

# config/database.yml

development:
 # first database configuration

development_sec:
 # second database configuration

Then in your model use this: 然后在模型中使用:

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

Or consider using a gem like connection_ninja 或者考虑使用像connection_ninja这样的宝石

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

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