When to use a "has_many :through" relation in Rails?

LuckyLuke picture LuckyLuke · Jul 22, 2012 · Viewed 84.8k times · Source

I am trying to understand what has_many :through is and when to use it (and how). However, I am not getting it. I am reading Beginning Rails 3 and I tried Googling, but I am not able to understand.

Answer

cpuguy83 picture cpuguy83 · Jul 22, 2012

Say you have these models:

Car
Engine
Piston

A car has_one :engine
An engine belongs_to :car
An engine has_many :pistons
Piston belongs_to :engine

A car has_many :pistons, through: :engine
Piston has_one :car, through: :engine

Essentially you are delegating a model relationship to another model, so instead of having to call car.engine.pistons, you can just do car.pistons