DEV Community

Kailana Kahawaii
Kailana Kahawaii

Posted on

Using the Active Storage Gem to Upload Photos

While working on a meal-tracker app, I discovered that allowing users to upload a photo was a fundamental, and not so difficult, feature to implement in Rails.

In this post, I will cover:

  1. adding the Active Storage gem to your gem file
  2. creating a macro for attaching that photo to a class
  3. using a form to allow the user to upload a photo

Active Storage Gem

Rails comes with an active storage gem that you can read about here. If you are adding it manually, simply add the gem to your gem file and run bundle install. You may be prompted on where you want to store that data. Choose the option that works for you.

The has_one_attached Macro

The next step is to set up that association on the model. I knew I wanted the posts to have pictures attached to them. The has_one_attached allows macro allows the pic to be associated with the Post class. Keep in mind that a post is created with a pic in this case, allowing with many other attributes.

a has_one_attached macro added to the Post model

Want to allow more than one image? Use the has_many_attached macro instead.

Form and Post

Finally, it’s time to write the form that will allow our user to upload a pic. I created a _form.html.erb in my views/posts folder to do this and added a file_field to a form_for.

f.file_field added to a form_for

When I click on the Choose File button, I’m prompted to upload a photo from my computer. Now, when I create a post, the picture loads alongside the post!

The file_field in action

However, what if the user chooses not to upload a pic? You can take care of that logic by using a simple if statement. First, the .attached? method will check to see if an attachment was made. If it evaluates to true, it will display the image. If there’s no image to display, it will display the next attribute, a summary in this case.

if statement to prevent errors

Uploading photographs with Ruby on Rails is surprisingly simple process but offers a lot of customization. Don’t be afraid to use it in your next project!

Top comments (0)