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
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
There is a presentation here that discusses multi-tenanted applications. It has some interesting ideas to utilise database schemas, particularly for postgres.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.