Rails has many through

Michael
1 min readFeb 4, 2022

The has many through association is used similar to a regular has many but with the added benefit of the association model when you need to use it.

For this example we are going to be looking at a User, Coin, Position and Portfolio model to show the power of the has many through association.

class User < ApplicationRecordhas_one :portfoliohas_many :positions, through: :portfoliohas_many :coins, through: :positionsend

Above is an example of a model that has many coins through positions.

class Coin < ApplicationRecordhas_many :positionshas_many :portfolios, through: :positionsend
class Position < ApplicationRecordbelongs_to :portfoliobelongs_to :coinend
class Portfolio < ApplicationRecordbelongs_to :userhas_many :positionshas_many :coins, through: :positionsend

The position model is the join table between Coin and Portfolio noted by the two foreign keys (portfolio_id, coin_id)

class CreatePositions < ActiveRecord::Migration[6.1]def changecreate_table :positions do |t|t.integer :quantityt.integer :cost_basist.integer :portfolio_idt.integer :coin_idt.timestampsendendend

The has many through association can be very useful to easily access associated data for complex applications!

To view our associated data in the positions controller we need to first find our User then return our positions in JSON.

class PositionsController < ApplicationControllerdef indexpositions = current_user.positionsrender json: positionsenddef current_userUser.find_by(id: session[:user_id])end
end

These two methods will allow us to fetch all of our current users positions so we can display them in our application. Thank you for taking the time to read my blog about the has many through association, hope it was of use!

--

--