代码之家  ›  专栏  ›  技术社区  ›  Dean Radcliffe

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

  •  2
  • Dean Radcliffe  · 技术社区  · 14 年前

    假设一个列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来影响这种行为?

    2 回复  |  直到 14 年前
        1
  •  0
  •   Steve Weet    14 年前

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

        2
  •  1
  •   Salil    14 年前
    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