如何使用 Active::Record 让数据库显示为由某些列分区
假设 client_id 列在我们的数据库中无处不在,并且对于给定的会话或请求,我们将始终处于客户端的“上下文中”。
有没有一种方法可以模拟将每个客户端的数据存储在单独的数据库中,同时将它们保存在同一个表中以简化数据库管理?我想要的与默认范围类似,但由于它会针对每个请求而更改,因此无法在加载时修复。
# invoices table data
# -------------------
# id client_id amount
# 1 1 100.00
# 2 2 100.00
with_client( Client.find(1) ) do
Invoices.all # finds only invoice 1
Invoices.find(2) # finds nothing or raises
end
我如何使用 ActiveRecord 做到这一点,或者在什么时候我可以通过手术改变 AR 来影响这种行为?
额外要点:我想阻止更新此 client_id 列 - 它应该在创建时修复
Suppose a column client_id is ubiquitous through out our database, and for a given session or request, we will be 'in the context' of a client the whole time.
Is there a way to simulate having each client's data stored in a separate database, while keeping them in the same table for simpler database-management ? What I want is similar to a default scope, but since it will change for every request, it cant' be fixed at load-time.
# invoices table data
# -------------------
# id client_id amount
# 1 1 100.00
# 2 2 100.00
with_client( Client.find(1) ) do
Invoices.all # finds only invoice 1
Invoices.find(2) # finds nothing or raises
end
How can I do this with ActiveRecord, or at what points could I surgically alter AR to affect this behavior ?
Extra points: Id like to prevent the updating of this client_id column - it should be fixed at create-time
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此处有一个讨论多租户应用程序的演示文稿。它有一些利用数据库模式的有趣想法,特别是对于 postgres。
There is a presentation here that discusses multi-tenanted applications. It has some interesting ideas to utilise database schemas, particularly for postgres.