A concrete example:
We’re building a system to organize the information about workshops
being held in various conventions. A convention has more than one
workshop, and each workshop can be held in more than one convention.
Also each workshop has a host, who is specific to a workshop being
held in a specific convention.
For example, Matz may host an “Introduction to Ruby” workshop in
RubyConf. And _why may host a the same workshop in RailsConf. This
operates through the join-model convention_workshops, which has the
following rows: convention_id, workshop_id, host_id, start_time. It
belongs_to :convention, :workshop, and :host.
Associations make it very easy to select by one association. If I want
to get the start_time of all workshops held on RubyConf Matz, I just
find RubyConf’s model instance and call
#convention_workshops.collect{|cw| cw.star_time} on it. But suppose we
want to select the start_time for only the workshops hosted by Matz on
RubyConf. How should we do that?
The SQL way would be:
SELECT convention_workshops.start_time
FROM convention_workshops, conventions, hosts
WHERE conventions.id=convention_workshops.convention_id
AND conventions.name=‘RubyConf’
AND convention_workshops.host_id=hosts.id
AND hosts.name=‘Matz’;
I’m pretty sure there shouldn’t be a need to write all that SQL for
Rails, especially after we bothered to set up all the association on
the code level. But what is it?