Uploading files to a Rails post

September 20, 2018

In this post, I’ll show you how to upload files, such as images, Word docs, and PDFs, to your Rails app. It’s super easy! To keep the example easy to understand, let’s use the tried-and-true method of adding an Image to a Post. Feel free to substitute your own resources for Image and Post, because the process will basically be the same across the board.

1. Run rails active_storage:install.

2. Then run rails db:migrate.

3. In your Post model (post.rb) and add has_one_attached, like so:

class Post < ApplicationRecord
  has_one_attached :image

4. Then, inside posts_controller.rb, you’d add :image to the post_params:

class PostsController < ApplicationController
  # ...other methods...


  def post_params
    params.require(:post).permit(:title, :body, :image)
    # allow users to upload multiple by using `images: []`

5. Add the upload fields to the Post’s _form.html.erb view.

<!-- Upload only one file -->
  <%= form.label :image %>
  <%= form.file_field :image %>

<!-- Upload multiple files -->
  <%= form.label :images %>
  <%= form.file_field :images, multiple: true %>

6. Now let’s show the files you uploaded inside show.html.erb.

<!-- Show a single image -->
<%= image_tag @post.header_image %>

<!-- List the names of multiple images -->
<% @post.images.each do |image| %>
  <%= image.blob.filename %>
<% end %>

<!-- Link to multiple attachments (great for PDFs!) -->
<% @post.files.each do |file| %>
  <%= link_to file.blob.filename, file %>
<% end %>

Next steps. For production, you’ll want to configure ActiveStorage to work with something like AWS or DigitalOcean. This isn’t too hard – you’ll just need to provide your information in a configuration file. You can learn more around 3:00 in this great video from GoRails.

I'm sharing everything I learn while building a software company. Join my newsletter to receive advice and opportunities that I never post publicly. Or learn more about me?