class Politician < ActiveRecord::Base
  belongs_to :state
end
jan = Politician.find_by(name: "Jan Schakowski")
illinois = jan.state
# => SELECT * FROM states WHERE id = #{jan.state_id}
class State < ActiveRecord::Base
  has_many :politicians
end
illinois.politicians
# => SELECT * FROM politicians WHERE state_id = #{illinois.id}
class Runner < ActiveRecord::Base
  has_many :participations
  has_many :races, through: :participations
end
class Participation < ActiveRecord::Base
  belongs_to :runner
  belongs_to :race
  # t.integer finish_time
end
class Race < ActiveRecord::Base
  has_many :participations
  has_many :runners, through: :participations
end
runner = Runner.first

runner.participations
# => SELECT * FROM participations WHERE runner_id #{runner.id}

runner.races
# => SELECT event_name FROM races JOIN participations
    ON participations.race_id = races.id
    JOIN runners ON participations.runner_id = runners.id;
# => ["100m", "200m"]

Active Record associations

By Isaac

Active Record associations

  • 430