Ruby on Rails Tutorial — Many to Many Relationships

Alex Merced - Tech Evangelist
1 min readJan 5, 2021

My Learning Ruby on Rails Video Playlist: https://www.youtube.com/playlist?list=PLY6oTPmKnKbYlAqVHgzZl5lou54bizdbV

Setup

This tutorial requires that you’ve already installed

  • ruby
  • rails

Create a new rails project

rails new invest_project --api

cd into the invest_project folder

Creating Our Models

Three Models

Investor — Investors who invest in companies Company — Companies who have investors Investments — junction of investors and companies

run the following commands…

rails generate scaffold investor name:stringrails generate scaffold company name:stringrails generate scaffold investment investor:references company:references

setup your database

rails db:createrails db:migrate

Outline your relationships

app/models/investor.rb

class Investor < ApplicationRecord
has_many :investments
has_many :companies, through: :investments
end

app/models/company.rb

class Company < ApplicationRecord
has_many :investments
has_many :investors, through: :investments
end

app/models/investment.rb

class Investment < ApplicationRecord
belongs_to :investor
belongs_to :company
end

Test it out!

rails console

run the following commands

#1 Create a new Investor
bob = Investor.create(name:"Bob")
#2 Invest in a new company
bob.companies.create("abc")
#3 Create a new company
def = Company.create("def")
#4 Add an investor
def.investors.create("Steve")
#5 see the results
Investor.all
Company.all
Invesment.all

--

--

Alex Merced - Tech Evangelist

Alex Merced is a Developer Advocate for Dremio and host of the Web Dev 101 and Datanation Podcasts.