Great Odin’s Raven!
Progressing through Phase 3 and learning Ruby, Sinatra, Active Record and a bit of SQL and Regex was by far the most in depth phase thus far in the Flatiron curriculum. However, now that I have become familiar with how to learn a new language, I was able to get through this phase without too many delays. I learned how and when to ask for help, google my questions and get through the labs in an efficient way.
Join tables in Active Record
One part of my phase 3 project that I found a bit confusing at first was the concept of Join tables. Join tables are used to store common data fields from two or more other tables. By doing this. the table creates a many to many relationship between data. The tables are essentially used to more easily reference a part of another table and combine them.
Sound confusing?
Hopefully it will all make sense shortly!
For my project, I needed to create a table that connected the Movies, and the Actors data. I did this by creating a Roles table, that has a ‘belongs to’ relationship with Movies and Roles using Active Record.
A join table works to account for a many-to-many relationship between two independent models/tables. For example, an Actor may have many Movies over the course of their acting career. Also, each individual Movie may have many Actors and thus many Roles. This is the basis of the many-to-many relationship. Each Role joins an Actor to a Movie.
Since the Roles model has the ‘belongs to’ relationship, the table that it is referencing needs to have the above ‘has many’ relationship.
As we remember from earlier, An individual Role ‘belongs to’ both the Actor and Movie, this is why we need the actor_id and the movie_id in the Roles table. Also, by including the Actor and Movie id’s in the roles table, now when I create a new Role, I can know which Actor and Movie that role is by referencing that that instance and using the specific id of the Actor and Movie. Heres what that looks like in the seeds file.
Now in the Rake console, the individual Actor and Movie can be found quickly. For example, more information on Anchorman can be accessed by searching Role.second.actor.name which returns:
Or, Role.second.movie:
And lastly, to find the genre: Role.second.movie.genre or Role.second.movie.genre.name:
By learning about and utilizing Join tables in our models, we can create much more complex projects and reference several layers deep between our data. It really is amazing!