Support for Delete Course and Unit Objects in Rails

Notes


In this lesson we're going to add some functionality that will help clean up all this messy testing data we've been creating along the way. We've made example Course objects and example Lesson objects, and if you're application is looking like mine, it's starting to create a lot of clutter.

In the Admin section of our application, there are links to delete the object but they won't work currently. That's because the links are pointing at the base controller for each object as opposed to the admin version of the object's controller. To fix this we just need to refactor the link_to helper method to point at the admin controller's delete action. If you can't remember the alias for the admin controller's paths feel free to type the following into your terminal:

rake routes

We'll want to find the prefix that matches the correct Controller#Action and append _path to the end of it for each of the Course, Lesson and Unit object's delete links.

Another problem we have to take into consideration is how object relationships work upon deletion. If a Lesson object belongs to a Course object and the Course object is deleted but not the Lesson object it can create some bad situations. To make sure this isn't a problem we have to add some code to each model file.

If a Lesson object is deleted, do nothing. If a Unit object is deleted, also delete the Lesson objects related to it. If a Course object is deleted, also delete the Unit objects related to it.

In our Unit model file, find the has_many statement and add the following code:

has_many :lessons, dependent: :destroy

And the same with the Course model file:

has_many :units, dependent: :destroy

Then for simplicity's sake, let's add a link to delete courses in the Admin::CoursesController index view. Right underneath the link_to for Edit course add another link_to:

<%= link_to 'Delete course', admin_course_path(course), method: :delete, class: 'btn btn-danger' %>

Now we have the ability to easily clean up all this messy data we've created to test our code with!

Happy coding!!!!