views:

29

answers:

2

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

+1  A: 
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
Salil
This. Don't try to pretend that clients don't exist; if everything is associated with the client, just bite the bullet and type `@client.invoice` each time you want it.
Matchu
That's the route we chose for XLsuite, and it's worked out well for us.
François Beausoleil
I can do the explicit solution, but I'm looking for something that will operate behind the curtains, to create 'apartments' of data in a configurable way. A given request, and possibly an entire process, would be bound to that apartments' scope.
Dean Radcliffe
A: 

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

Steve Weet