Connect Units Model to the Parent Course Model in Rails App


Now we have this idea that Course and Unit objects live in our application. Every Unit object belongs to a particular Course object  Any given Course object could have many Unit objects. What we want to do is have a way to display a list of all the Unit objects owned by a Course object.

Just like everything else, Rails makes this easy as pie. When working with an instance of a Course object you can list all of it's Unit objects by calling the units method on it.

<% @course.units %>

Calling the units method on a Course object returns an array of Unit objects who's course_id attribute is equal to the Course object's id attribute. 

We can use this powerful feature in a view to accomplish the goal of this lesson: listing all the Unit objects for a given Course object. 

Let's open app/views/courses/show.html.erb and call the units method on our Course instance variable and iterate over and create HTML to list each Unit. The cards we used in the Courses index view are easier on the eyes than the table Rails defaults to so let's use that HTML structure to display each Unit object.

Iterating over a course's lessons to display them

Also, the show.html.erb file in our app/views/units has a link pointing back to the Unit object's index action. We would like to change that link to point back at the Unit object's Course show action. Let's add just a smidgeon of styling while we're here as well.

Linking to a unit's course

Notice how it's singular when calling the method backwards. That's because a Unit object can only be tied to 1 Course object while 1 Course object can be tied to many Unit objects.

Now we can hop around units inside of a course and also the Unit objects logic is separated between admin's and not the same way we did with the Course object. We'll continue to add styling as we go.

Happy coding!!!!