Many-to-Many
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
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
end
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
end
class Section < ActiveRecord::Base
belongs_to :document
has_many :paragraphs
end
class Paragraph < ActiveRecord::Base
belongs_to :section
end
With :through => :sections specified, Rails will now understand:
@document.paragraphs
No comments:
Post a Comment