Skip to content

Instantly share code, notes, and snippets.

@pitosalas
Created October 8, 2022 00:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pitosalas/ac32e79ebc5c4763e27dd19e60003a53 to your computer and use it in GitHub Desktop.
Save pitosalas/ac32e79ebc5c4763e27dd19e60003a53 to your computer and use it in GitHub Desktop.
A solution to today's lab - Rails 7 Many to many
# to those of you who got stuck, here are some more hints. Note that there is more than one way to do this!
# Also note that I had to debug my solution a little too, I didn't get it the first few times!
#
# This is not one big file it is a series of key parts of the code
# Migrations
class CreateStudents < ActiveRecord::Migration[7.0]
def change
create_table :students do |t|
t.string :name
t.timestamps
end
end
end
class CreateStudents < ActiveRecord::Migration[7.0]
def change
create_table :students do |t|
t.string :name
t.timestamps
end
end
end
class CreateAdvisorAssignments < ActiveRecord::Migration[7.0]
def change
create_table :advisor_assignments do |t|
t.integer :student
t.integer :teacher
t.timestamps
end
end
end
# seeds.rb
10.times do
Student.create(name: Faker::Name.name)
Teacher.create(name: Faker::Name.name)
end
10.times do
AdvisorAssignment.create(student: Student.all.sample, teacher: Teacher.all.sample)
end
# models
class AdvisorAssignment < ApplicationRecord
belongs_to :student
belongs_to :teacher
end
class Student < ApplicationRecord
has_many :advisor_assignments
has_many :advisors, through: :advisor_assignments, source: :teacher
end
class Teacher < ApplicationRecord
has_many :advisor_assignments
has_many :advisees, through: :advisor_assignments, source: :student
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment