Thursday, 11 October 2012

Has Many Through Relationship


There are two ways to build a many-to-many relationship.

The first way uses a has_many association with the :through option and a join model, so there are two stages of associations.

A has_many :through association is often used to set up a many-to-many connection with another model. This association indicates that the declaring model can be matched with zero or more instances of another model by proceeding through a third model.

For example, consider a medical practice where patients make appointments to see physicians. The relevant association declarations could look like this:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments

has_many :through

The collection of join models can be managed via the API.  for example, if you assign

physician.patients = patients

new join models are created for newly associated objects, and if some are gone their rows are deleted.

Automatic deletion of join models is direct, no destroy callbacks are triggered.

The has_many :through association is also useful for setting up "shortcuts" through nested has_many associations. For example, if a document has many sections, and a section has many paragraphs, you may sometimes want to get a simple collection of all paragraphs in the document. You could set that up this way:

class Document < ActiveRecord::Base
  has_many :sections
  has_many :paragraphs, :through => :sections

class Section < ActiveRecord::Base
  belongs_to :document
  has_many :paragraphs

class Paragraph < ActiveRecord::Base
  belongs_to :section

With :through => :sections specified, Rails will now understand:


No comments:

Post a Comment