Rails foundationSort Order

Rails: Active Storage Basics (File Uploading)

Active Storage is now the preferred way to handle file uploads in rails. Whether you are handling images, documents or even videos Active Storage can help you.

Let's begin implementing file upload in our application

Setting up the Database Tables

Before we can use active storage in our app we need to add a couple of tables to our database.

rails active_storage:install

This will generate the migration file for us. Next we just run the migration.

rails db:migrate

That's it in terms of database setup.

Add Relation to Model

Now we can add the relationship to the model we want to allow uploading. Let's add a cover_picture to the Post model.

class Post < ApplicationRecord  # ...  has_one_attached :cover_picture  # ...end

Enabling Cover Picture at the Controller

Since we're using strong parameter for our controller we need to add the cover_picture to the list of allowed attributes

# app/controllers/admin/posts_controller.rbclass Admin::PostsController < Admin::BaseController  # ...    private    # ...    def post_params    params.require(:post).permit(      :state_event, :cover_picture,       :title, :body, tag_ids: => []    )  endend

Adding the File Field to the Form

In our form we need to add the file field (so we can browse and upload file)

# app/views/admin/posts/_form.html.erb<%= form_for [:admin, @post] do |f| %>  <div class='form-group'>    <%= f.label :cover_picture %>    <%= f.file_field :cover_picture %>  </div>  # ...<% end %>

We should now be able to browser to the form and upload a cover picture.