🕒10-20 min

In this stretch feature, you'll learn about Active Storage, which is Rails' built-in solution for handling file attachments to models.

🏁 Goal

Allow users to upload profile pictures and display them alongside their messages!

💽 Installing Active Storage

To start using Active Storage, you need to run a command in our Whales terminal to create the tables that Rails will use to keep track of your attachments:

rails active_storage:install

Psst... this creates a migration. Make sure to run them after!

🗺 Updating our User model

To tell Rails that we want an attachment stored on a model, no migration is necessary. All we need to do is update our model file to include some information that a User can have a file attached.

Add the following to app/models/user.rb to tell Rails that we should be able to attach an image to a User record:

has_one_attached :image

That's it for our model changes! Think about why this may have been a model change instead of a schema change.

📤 File uploads in forms

Rails has some built-in form utilities as a part of Active Storage for handling file uploads.

Let's use them inside of our Devise form for updating a user's profile (this is in app/views/devise/registrations/edit.html.erb)

<div class="field">
  <%= f.label :image %>
  <%= f.file_field :image, accept: "image/png,image/gif,image/jpeg" %>
</div>

We need to update one more thing in our controller to allow this to work, which is permitting parameters in our form, like we did in the Authentication section. Try permitting the new field we created yourself!