Setting up

To start you should declare in your config/storage.yml file your Active Storage services, one for each service that you use in your application.

Please, note that for the sake of this article, I’ll just be showing configurations for uploading the files to the same directory as your application, in your local disk. If you prefer to use it to upload to any cloud provider please refer to the docs.

local:

service: Disk

root: <%= Rails.root.join("storage") %>

After you declared every service that you’ll be using it’s time to tell your application what service should be used on each environment. In this article, I’m going to configure my development environment to use my local storage service. In order to achieve this add the following line to config/environments/development.rb :

# Store files locally.

config.active_storage.service = :local

Use it

Now that we managed to configure Active Storage it’s time to start using it! One of the advantages of it is to easily create a relationship between the uploaded asset and your Active Record models, as stated at the beginning of this article, so we’re to take advantage of it. I have a Speakers model in which I intend to add an avatar to each of the speakers.

We’ll start by informing my Speakers model that it will have a one-to-one relationship with the corresponding uploaded avatar. My model will look like:

class Speaker < ApplicationRecord

has_one_attached :avatar

end

Then my Speakers controller will accept an avatar to be uploaded. My speaker_params will now look like:

def speaker_params

params.permit(:name, :company, :email, :avatar)

end

The file should now look like this:

class SpeakersController < APIController

before_action :set_speaker, only: %i[show update destroy]



render json: @

end def index @speakers = Speaker.allrender json: @ speakers , status: :okend



render json: @

end def create @speaker = Speaker.create!(speaker_params)render json: @ speaker , status: :createdend

render json: @

end def showrender json: @ speaker , status: :okend



head :no_content

end def update @speaker .update(speaker_params)head :no_contentend



head :no_content

end def destroy @speaker .destroyhead :no_contentend private def speaker_params

params.permit(:name, :company, :email, :avatar, :social_media)

end



end

end def set_speaker @speaker = Speaker.find(params[:id])endend

I have to specify on my request body a field named avatar and its value will be a file, that’s going to be used as the speaker avatar.

After you finish your POST request and you navigate to the storage directory you’ll see a newly created directory containing your uploaded file. If you wish to verify that the file is linked to your speaker you can start rails console and type:

Et voilá, Active Storage is configured and ready to be used.