Add a default condition in active record

I need to add to every retrieved record a condition “client=xxx”. How do
I alter default conditions globally when retrieving records in

Some background:

I’ve built a website / web service to be used just by a company. Now
we’re trying to make the service available to other companies. The
accounts will share the same codebase (think The
options are:

  1. Multiple databases (one for each account)
  • easy to implement at the beginning
  • hell to maintain
  1. The same database for all the data + some ruby magic
  • easier to maintain in the long term (?)
  • how to do it?
    I will have a subdomain or a url parameter that will tell the name of
    the company using our software. When reading records I need to override
    the default conditions to add a parameter “client=company_id”. I will
    add a before_filter on save in every model to add

You can look at Model.with_scope. Also, I do something similar to what
you are talking about. I have a user, that belongs to a company. Then
company has_many widgets. Every time I create or access a widget, I do
it through the association which adds the condition automatically like:
or => [‘widget_name =

The resulting sql for both of the above calls will have “company_id =
users_company_id” added where users_company_id is the numerical id of
the company.

You can read up on with_scope as it may do better for you, depending on
what you are wanting to do:

Hope this helps.

Constantin G. wrote:

add a before_filter on save in every model to add


William P.