如何使用 Active::Record 让数据库显示为由某些列分区

发布于 2024-09-09 00:15:18 字数 585 浏览 5 评论 0原文

假设 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落墨 2024-09-16 00:15:18
class Client < ActiveRecord::Base
  has_one :invoice, :dependent => :destroy
end

class Invoice < ActiveRecord::Base
  belongs_to :client
end

In controller

   @client= Client.find(1)
   @client.invoice #finds  id  =1     client_id  =1   amount=100.0
class Client < ActiveRecord::Base
  has_one :invoice, :dependent => :destroy
end

class Invoice < ActiveRecord::Base
  belongs_to :client
end

In controller

   @client= Client.find(1)
   @client.invoice #finds  id  =1     client_id  =1   amount=100.0
日记撕了你也走了 2024-09-16 00:15:18

此处有一个讨论多租户应用程序的演示文稿。它有一些利用数据库模式的有趣想法,特别是对于 postgres。

There is a presentation here that discusses multi-tenanted applications. It has some interesting ideas to utilise database schemas, particularly for postgres.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文