This course will be retired on June 1, 2025.
Bummer! You have been redirected as the page you requested could not be found.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Polymorphic belongs_to associations allow a model to belong to more than one type of other model.
You can set up a movie database app like we use in the video with these terminal commands:
rails new mdb
cd mdb
bin/rails g scaffold Movie title:string duration:integer
bin/rails g scaffold Show title:string episodes:integer
bin/rails g scaffold Actor name:string
bin/rails g migration AddProductionToActor production_id:integer production_type:string
bin/rails db:migrate
If you prefer, there's an alternate syntax for adding the _id
and _type
reference fields to the migration:
bin/rails g migration AddProductionToActor production:references{polymorphic}
Now we need to set up the polymorphic association in the model classes:
class Movie < ApplicationRecord
has_many :actors, as: :production
end
class Show < ApplicationRecord
has_many :actors, as: :production
end
class Actor < ApplicationRecord
belongs_to :production, polymorphic: true
end
With all that set up, you can add an Actor
to either a Show
or a Movie
in the Rails console:
show = Show.create(title: "Game of Thrones")
show.actors
show.actors.create(name: "Peter Dinklage")
show.actors.create(name: "Lena Headey")
pp Show.first.actors
Actor.first.production
movie = Movie.create(title: "Fight Club")
movie.actors.create(name: "Brad Pitt")
movie.actors.create(name: "Edward Norton")
Movie.first.actors
pp Actor.all
You can read more about using polymorphic associations within your app here.
[/SCREENCAST]
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up