Adding photos to your Rails app with Active Storage!
Rails has probably become my favorite language to date, what with its ‘magical’ properties and abundance of methods and gems. If you’re looking to spice up your project with the ability to add photos, here’s where Active Storage comes in!
Step 1: Setting up Active Storage
This is of course, assuming you’ve already set up your rails application — and with any gem you’ll be installing, make sure to type into your console:
rails active_storage:install
rails db:migrate
Once everything has been properly installed and you know which model you’d like to attach photos to, we’ll use the has_one_attached macro provided to us by ActiveStorage.
2. Setting up Attachments (M):
Though AS has quite a few macros you can use, we’ll keep it simple and use their has_one_attached macro which basically sets up a one-to-one mapping between records and files. This means each record can have one file attached to it.
The first thing you’ll want to do is create the association in your model file. In my case, I wanted my posts to have photos so I added the macro with the :picture
attribute provided to us.
3. Whitelisting Parameters (C):
Next we’ll want to head over to our controller and add the parameter :picture
to our strong params.
Side note: Strong params are a really cool rails feature that prevents assigning request parameters to objects unless we explicitly allow them. In this case, the :picture
param is what is allowed and will be shown within our app.
4. Adding Pictures to the Form and Show (V):
First we’ll want to create a form in our new.html.erb
using the form_for
tag provided to us by rails.
Then we’ll add in the :picture
param! It’s the same as adding in any model attribute when creating your forms.
The final piece of the puzzle is simply to add in the image_tag
helper to display our image in the show page.
This one is simple enough, I defined a width of 200px and used one of ActiveStorage’s methods attached?
which checks and return true if an attachment has been made.
And it’s done! Make sure to check out the Active Storage readme if you’d like to explore more of their macros!