2010-07-09 48 views
2

假设一列client_id在我们的数据库中无处不在,并且对于给定的会话或请求,我们将在客户端的“上下文中”整个时间。如何使数据库看起来被Active :: Record的某些列分区

有没有一种方法来模拟将每个客户端的数据存储在单独的数据库中,同时将它们保留在同一个表中以实现更简单的数据库管理?我想要的与默认范围类似,但由于它会针对每个请求进行更改,因此无法在加载时进行修复。

# 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列的更新 - 它应该被固定在创建时

+0

关于此场景的一些其他想法:http://www.linkedin.com/answers?viewQuestion=&queryID=698205&askerID=3854479 – 2010-07-09 20:48:25

+0

这个其他堆栈溢出问题也非常相似:http://stackoverflow.com/questions/1603178/rails-best-practice-to-scope-queries-based-subdomain – 2010-07-09 20:50:40

回答

0

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

1
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 
+0

This。不要试图假装客户不存在;如果一切都与客户端相关联,只需咬住子弹并在每次需要时输入“@ client.invoice”即可。 – Matchu 2010-07-09 15:02:32

+0

这就是我们为XLsuite选择的路线,它对我们来说很好。 – 2010-07-09 16:03:20

+0

我可以做明确的解决方案,但我正在寻找可以在窗帘后面操作的东西,以可配置的方式创建“公寓”数据。一个特定的请求,并可能是一个完整的过程,将被绑定到该公寓的范围。 – 2010-07-09 20:36:10

相关问题