Add Image Attachment to Course Model


At this point our application is really coming along! We've built a lot of functionality and hopefully you've learned quite a bit working through this process. In this lesson we're going to be improving the Course  and Lesson model objects by adding the ability to attach images to them. Attaching the image will give us the ability to display dynamic images for a Lesson or Course model object with minimal code.

To get started let's hop in our model files for the Course and Lesson objects and add the code that allows us to attach a file.

has_one_attached :image

Also, we'll need to allow the file to make it through the controller by including it in the strong params. We'll need to add :image in both Admin::LessonsController and Admin::CoursesController.

Finally, we need to move into the form partial files for each object and add an input field for the file upload.

<div class="form-group">
  <%= form.label :image %>
  <%= form.file_field :image, class: 'form-control' %>

Just like with the controller and model changes, we need to make this change to the Lesson and Course object's form partial files. 

After we finish these steps we should be able to visit the Course object's form in our browser and upload a picture. I grabbed one from but any image will do for the sake of testing. If the Course saved with the file uploaded then everything is working fine, but we can't see our image displayed. Let's jump over to our Course object's show view and remedy that problem.

Just like with the videos in our Lesson show view, we only want to display the image if the Course object has one attached. Let's wrap our logic an if statement right above the h1 tag that's displaying the Course object's title. Then we will create an img tag, feed it the image source URL and do some in-line styling.

<% if @course.image.attached? %>
  <img src="<%= url_for(@course.image)" width="600">
<% end %>

So now we have the ability to attach images to our Course and Lesson objects and we're displaying the Course object images on it's show page!

Happy coding!!!!