Sitemap

Ruby on Rails Has Many Through Association

2 min readOct 25, 2022

--

What is Association in Rails?

Associations within Rails is a connection between two Active Record models to make operations simpler and easier in your code.

There are many associations in rails such as:

  • One to One
  • One to Many
  • Many to Many
  • Polymorphic One to Many

This blog will focus on the Many to Many association specifically the Has Many Through.

What is Has Many?

The has_many through relationship within rails allows users to set an object to have many of something and the receiving object can have many of the object. For example, a bee can have many flowers and a flower can have many bees.

Press enter or click to view image in full size

Creating 3 Models:

We need to generate 3 models to create the has_many through relationship by typing the following within terminal:

rails g model Bee name id:integer
rails g model Flower name id:integer

Now that a Bee has many flowers and a Flower has many bees we need to generate our third and most important table since it will essentially link the Bees to the Flowers.

rails g model Role bee_id:integer flower_id:integer

Modify the Model:

Within the model we will then configure a has_many through association between bee, flower, and role. The association declarations would look like this:

Get Leon Wong’s stories in your inbox

Join Medium for free to get updates from this writer.

bee.rb

class Bee < ActiveRecord::Base
has_many :roles
has_many :flowers, through: :roles
end

flower.rb

class Flower < ActiveRecord::Base
has_many :roles
has_many :bees, through: :roles
end

role.rb

class Role < ActiveRecord::Base
belongs_to :bee
belongs_to :flower
end

The user can also read this example as:

Bees through roles have many flowers that they are assigned too, while flowers have many bees through roles. Both flowers and bees can have many roles as well.

The Role table is what connects the bee and flower through their id (bee_id and flower_id).

Press enter or click to view image in full size
The More You Know 🌈⭐️

--

--