Implementing File Attachments with Active Storage in Rails 5.2

Notes


In this lesson we will be addressing the need for uploading files to our application. For the longest time you used a third party tool called Paperclip to do this, but starting with Rails 5.2 a system was implemented into native Rails to accomplish this called ActiveStorage. To get started with ActiveStorage we need to type a command into our command line:

rails active_storage:install

This command will create a new migration file so we'll need to run the migrate command for the changes to take effect.

rake db:mgirate

The next thing we need to do is open the app/models/lesson.rb file and add a line of code that tells Rails the Lesson model object can have an attached file.

has_one_attached :video

We also need to allow our form to have way to take in what file should be uploaded. You probably guessed it, but we can accomplish this by using a Rails helper method in the Lesson object's form partial.

<%= form.file_field :video, class: 'form-control' %>

And now that we're passing in the video attribute to the controller from the form, we need to okay the video attribute as a param in the lesson_params method. This is in the Admin::LessonsControllers.

After uploading a file we can check the storage folder in our application's root directory to see that it was successfully uploaded. Soon we will work on displaying videos we upload and, as always, continue to improve the application's styling.

Happy coding!!!!