views:

155

answers:

2

I'm setting up a SaaS style website wherein I will have multiple clients all managing their workflows and data on the same site -- and thus the same database.

I'm not even sure if there is a word for this concept, but is there any established way of auto-segregating the data so that any ActiveRecord calls to the database are filtered/restricted by the correct client_id of the user that is logged in?

The straightforward way would be of course to just add a "where client_id = ?" and put in the user's client id... onto the end of every single ActiveRecord request.

Is there any before filter idea for the Models, so that any find method (including the dynamic ones) would tack on the client_id to them automatically?. So I could just do Model.find_by_what_I_want(foo), and it would automatically know to limit that to only records owned by the correct client id even though I didn't specify it explicitly?

+9  A: 

If you're using Rails 2.3+, you have the luxury of default scopes:

class Model < ActiveRecord::Base
  default_scope :conditions => ['client_id = ?', client_id]
end

You'd have to make sure client_id is set somewhere in the init process.

This would ensure that all db queries in that model use the client_id condition.

Pras
Perfect! Thanks
I would use a Hash for the conditions Hash, which also ensures newly created records would receive the correct ID automatically:default_scope :conditions => {:client_id => client_id}
François Beausoleil
A: 

How about adding a new database for every customer? This way separation of customer is more concrete, and errors, where customers could other customer's data, are less likely.

Juha Syrjälä