Ruby on Rails Tutorial - Many to Many Relationships

Alex Merced - Nov 11 '20 - - Dev Community

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
Enter fullscreen mode Exit fullscreen mode

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:string
Enter fullscreen mode Exit fullscreen mode
rails generate scaffold company name:string
Enter fullscreen mode Exit fullscreen mode
rails generate scaffold investment investor:references company:references
Enter fullscreen mode Exit fullscreen mode

setup your database

rails db:create
Enter fullscreen mode Exit fullscreen mode
rails db:migrate
Enter fullscreen mode Exit fullscreen mode

Outline your relationships

app/models/investor.rb

class Investor < ApplicationRecord
    has_many :investments
    has_many :companies, through: :investments
end
Enter fullscreen mode Exit fullscreen mode

app/models/company.rb

class Company < ApplicationRecord
    has_many :investments
    has_many :investors, through: :investments
end
Enter fullscreen mode Exit fullscreen mode

app/models/investment.rb

class Investment < ApplicationRecord
  belongs_to :investor
  belongs_to :company
end
Enter fullscreen mode Exit fullscreen mode

Test it out!

rails console
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .