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
ActiveRecord?

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 Salesforce.com). 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
    “self.client=company_id”.

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:

current_user.company.widgets.find(id)
or
current_user.company.widgets.find(:conditions => [‘widget_name =
?’,foo])

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:
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001024

Hope this helps.

Constantin G. wrote:

add a before_filter on save in every model to add
“self.client=company_id”.


Sincerely,

William P.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs