简体   繁体   English

Rails应用程序具有多个数据库连接

[英]Rails application with multiple database connections

I have a single Rails instance with a multiple database connection which serves two different services. 我有一个带有多个数据库连接的Rails实例,它提供两种不同的服务。 Let's say it serves service A and service B. Service A requires connection to database A' and Service B requires connection to database B' . 假设它服务于服务A服务B.服务A需要连接到数据库A' ,服务B需要连接到数据库B' Most of the tables in A' and B' are identical (table name, schema). A'B'中的大多数表都是相同的(表名,模式)。 Eg. 例如。 Database A' and B' both have a table User with identical schema. 数据库A'B'都有一个具有相同模式的表User Currently my model for user looks like: 目前我的用户模型如下:

class User_A < ABase #connects to A'
    self.table_name = "user"

    def foo
      ...
    end

end

class User_B < BBase #connects to B'
    self.table_name = "user"

    def foo
      ...
    end

end

Inside controller I have to do something like: 内部控制器我必须做的事情如下:

if is_A?
 user = User_A.find(123)
else
 user = User_B.find(123)
end

Is there any better way to handle such situation in rails which would minimize code repetition? 有没有更好的方法来处理轨道中的这种情况,这将最大限度地减少代码重复?

Multitenancy for Rails and ActiveRecord

Apartment provides tools to help you deal with multiple tenants in your Rails application. 公寓提供工具来帮助您处理Rails应用程序中的多个租户。 If you need to have certain data sequestered based on account or company, but still allow some data to exist in a common tenant, Apartment can help 如果您需要根据帐户或公司隔离某些数据,但仍允许某些数据存在于共同租户中,公寓可以提供帮助

gem 'apartment'

Apartment gem This gives you access to use multiple db in most easy way as possible. Apartment gem这使您可以以最简单的方式访问多个数据库。

Apartment::Tenant.switch db_name

Now You can access like this 现在您可以像这样访问

class User < ABase

    def foo
      Apartment::Tenant.switch db_a
      #Do what you update in db_a

      Apartment::Tenant.switch db_b
      #Do what you update in db_b
    end

end

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

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