DEV Community

Cover image for Ruby on Rails Tutorial - Many to Many Relationships
Alex Merced
Alex Merced

Posted on

1

Ruby on Rails Tutorial - Many to Many Relationships

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

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or a friendly comment!

Okay.