has_many :through
at a high-level.
A has_many :through
association is how we setup many-to-many connections with another model. When we define a has_many :through
relationship on a model, we’re saying that we can potentially link the model to another model by going through a third model. I think the Rails guides do a great job of illustrating an example of how to use this relationship. Let’s think of a different example. Say we have a company, a company has employees through an employment.
class Company < ApplicationRecord
has_many :employments
has_many :employees, through: :employments
end
class Employment < ApplicationRecord
belongs_to :employee
belongs_to :company
end
class Employee < ApplicationRecord
has_many :employments
has_many :companies, through: :employments
end
Our migrations would look like this:
class CreateCompanies < ActiveRecord::Migration[6.0]
def change
create_table :companies do |t|
t.string :name
t.timestamps
end
create_table :employees do |t|
t.string :name
t.timestamps
end
create_table :employments do |t|
t.belongs_to :employee
t.belongs_to :company
t.datetime :start_date
t.datetime :end_date
t.string :role
t.timestamps
end
end
end
When an employee “leaves” a company, we don’t have to create the employee all over again. We make a new employment linked to their employee record and their new company.