What did we just do? Check out the diagram in the browser:
- We created three models -
Movie
,Actor
, andPart
. - In the models, we used the
has_many :through
association to connect theMovie
model to theActor
model through thePart
model.
In this way, the has_many :through
association sets up a many-to-many relationship between movies and actors.
Instructions
Now that there’s an association between Movie and Actor, let’s continue and add columns to the migration files:
Open the migration file in db/migrate/ for the movies table, and add the following columns:
- a
string
column calledtitle
- a
string
column calledimage
- a
string
column calledrelease_year
- a
string
column calledplot
Next in the migration file for the actors table, and add the following columns:
- a
string
column calledfirst_name
- a
string
column calledlast_name
- a
string
column calledimage
- a
string
column calledbio
Then in the migration file for the parts table, add the following lines. They add foreign keys that point to the movie and actor tables.
t.belongs_to :movie, index: true t.belongs_to :actor, index: true
Run the migration to update the database with the three tables.
Open up db/seeds.rb. We’ve added a few items here to seed the database with movies and actors. Run bundle exec rake db:seed
to seed the database with the data in db/seeds.rb.