Re: Additional database condition in -all- queries?

Justin Forder
2005-12-02T07:08:45Z

Jake Janovetz wrote:
> Hello-
>
> Regarding a web application that is provided to several different
> customers, my original plan was to have separate databases for each
> customer.  The Rails app would then choose the right database determined
> by the customer''s login.
>
> Others suggested rolling everyone''s data into the same database.
My
> question regarding this method is how to segregate the data.  I could
> add a condition like "WHERE customer_id = ?", but it would nice
to
> somehow add this to -all- queries (DRY, right?).  Is this possible?
>
>    Jake
>

David Heinemeier Hansson described how this is done in applications like
Basecamp, in the thread "Basecamp database model".

The question being asked was:
"It seem like if we are using the framework extracted from the Basecamp
app it would be good to know a little about the database model
structure. In particular I wonder how multiple projects are handled for
one account. I would like to have multiple storefronts for an ecommerce
application and think this might be similar to multiple projects in
basecamp."

DHH''s answer:

A few clues:

* http://wiki.rubyonrails.com/rails/pages/HowToUseSubdomainsAsAccountKeys
* http://dev.rubyonrails.org/svn/rails/plugins/account_location/

This is naturally not verbatim, but for this discussion it''ll serve:

class Account < ActiveRecord::Base
   has_many :projects
end

class Project < ActiveRecord::Base
   belongs_to :account
   has_many :milestones
end

class Milestone < ActiveRecord::Base
   belongs_to :project
end

So you can say Account.find(:first).projects.first.milestones to get
all the milestones of the first project that belongs to the first
account.