在多个数据库上使用 ActiveRecord [英] Using ActiveRecord on Multiple Databases

查看:43
本文介绍了在多个数据库上使用 ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个将与现有系统集成的工资系统.原来的系统有一个主数据库,负责用户管理和一些全局配置,下面有多个结构相同的数据库,基本上每个数据库都是一个公司的工资数据库,所有这些都绑定到主数据库,因为它属于一个父数据库拥有许多子公司的公司,每个子公司都有自己的人力资源部门.

I am writing a payroll system that will integrate with a pre-existing system. The original system had a master database that handled user management and some global configuration, below that there are multiple databases each identical in structure, basically each database is one companies payroll database, all these are tied to the main database because it belongs to a parent company who has many subsidiaries each with their own HR department.

我想知道是否有任何方法可以基于 cookie 或其他存储他们希望连接的公司的方法,使用 before 过滤器根据他们的输入动态更改 ActiveRecord 的目标数据库?

What I was wondering is if there is any way that I can, based on either a cookie or another method that stores what company they wish to connect to, dynamically change the ActiveRecord's target database based on their input using a before filter?

这是一个例子:

用户 A 登录到该站点,页面加载了用户有权访问的可用公司,然后用户将选择一家公司,他们在该公司拥有管理员权限,在运行该操作之前,他们添加了一名员工,rails 会将连接切换到适当的数据库,然后添加记录.

User A logs in to the site, page loads with available companies that the user has permission to access, user will then select a company, they have admin privileges in that company, they add an employee, before that action is run, rails will switch the connection to the appropriate database then add the record.

推荐答案

您可以使用 ActiveRecord::Base#establish_connection,连接到所需的数据库.

You can use ActiveRecord::Base#establish_connection, to connect to the desired database.

您可以将数据库凭据作为 Hash

You could pass the db credentials to establish_connection as a Hash

establish_connection(
  adapter: 'mysql2',
  encoding: 'utf8',
  pool: 5,
  username: 'me',
  password: 'mypassword'
)

还有更多示例此处

这篇关于在多个数据库上使用 ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆