Storing images with Active Storage in Rails

peter chendipeter chendi
4 min read

Are you struggling with uploading multiple images to your Rails application? Worry no more! In this article, I will guide you through the process of uploading multiple images to your Rails API application.

Active storage

Active storage makes it easy for us to upload files like images, and documents to cloud storage services like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage. This is done in the production environment. In the development and test environment, active storage provides us with a local disk service where you can easily store your images locally when developing your project. It allocates each image to a particular record with the help of Active Record objects.

Article workflow

In this article, we will focus on uploading images to Active Storage in the development environment. Stay tuned for the upcoming Part 2, where we will dive into uploading images in the production environment.

To illustrate the implementation of Active Storage, we will create a gallery API Rails application. This application will empower users to create accounts and post galleries of captivating images.

Implementing active storage

Let's get started with creating our Rails application. Open your terminal and execute the following commands:

rails new blogApi --api --database=postgresql

— api to let rails know that we will be creating API for this project and — database=postgrsql to specify the database we will be using.

Install dependencies

open the project folder and install all the dependencies with the commands below

cd galleryApi
bundle install

Models and controllers

rails generate scaffold users name:string email:string
rails generate scaffold galleries title:string description:string user:references

These commands automatically generate the models and controllers for users and galleries in our project.

Note: We intentionally omit the "avatar" attribute in the user table and the "pictures" attribute in the gallery table. Active Storage will handle these attributes and associate them with the corresponding records in the tables, leveraging the power of Active Record.

Install active storage

Run this command in the terminal to install active storage

rails active_storage:install

This command generates a migration file that creates 3 tables namely: active_storage_blobs, active_storage_attachment, and active_storage_attachments. These tables help active storage to easily upload and attach your files to the responding table for example upload an avatar for a user table.

For more info about each of the tables, you can visit this link

Create database

Ensure your database is set up correctly by running the following command:

rails db:create db:migrate

This command creates the necessary tables in the database for our project. Confirm your schema file matches the expected structure.

If your schema looks the same then you are good to go!

modify the models

In the user and gallery models, we need to make specific modifications to support file attachments. Update the models as follows:

In the user model add this code has_one_attached :avatar

Which means we will upload just one picture for the avatar. The user model should look like this.

In the gallery model add this code has_many_attached :pictures

With this code, we will be able to upload more than one picture. The gallery model should look like this.

Modify the controllers

Add avatar in the user params method and take note on the params.require as shown below

Add pictures[] in the gallery params as shown below

Generate Serializers

Serializers provide a flexible way to customize how JSON is rendered by our controllers. In this case, we want the controllers to render the URLs of the images in JSON format.

let's install the dependencies by adding this code in our gemfile and running bundle install

gem 'active_model_serializers'

Run these commands in the terminal

rails g serializer user
rails g serializer gallery

In the generated user_serializer.rb modify it to like the code below

In the generated gallery_serializer.rb modify it to like the code below

Set routes

The last thing to do is to set the default route of the URLs of the images.

go to the route.rb and add this line of code default_url_options :host => "localhost:3000" as shown below

Note: change the port number base on your default port number as you can see mine is 3000

Test Apl endpoints

I will be using a vs code extension called thunder client to test it. You can also use Postman to do it.

Let's start our server

rails s

let's test the endpoint to create a new user and upload an avatar

As you can see we have the avatar url. Take note of the API endpoint I'm using here. If you want to see all the endpoints run rails routes in your terminal.

let's test the endpoint to create a new gallery and upload pictures

I have uploaded two pictures for this gallery as you can see their URLs. You can test it by copying the URL and paste in your browser to see if the image is uploaded successfully.

Conclusion

In this post, we successfully upload images with active storage on the development environment. In the next post, I will show you how you can upload images in the production environment.

1
Subscribe to my newsletter

Read articles from peter chendi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

peter chendi
peter chendi

Hello, I'm Peter Chendi, a full-stack developer who is obsessed with building high-quality, Well organized, and maintainable web applications that provide exceptional user experiences using different languages and frameworks like Javascript, React, Redux, Ruby, Ruby on Rails, etc following the best code practices. Here is a link to my portfolio https://peter-portfolio-chendi.netlify.app/ In my previous role as a full-time Microverse student, I spent months immersed in a remote development environment, collaborating with amazing peers around the world with diverse backgrounds and cultures to develop a variety of web applications, blogging apps, and more. Here is a link to my GitHub: https://github.com/anyepeter. I am passionate about developing scalable software, as well as user-friendly and responsive websites, and I enjoy learning new technologies. I'm eager to collaborate with a talented team of developers, designers, and support specialists to build tools and products that empower businesses to deliver better customer experiences and streamline their support operations. Regarding my expertise, I have experience with; Programming languages: Javascript, Ruby, PHP Libraries & Frameworks: React, Ruby on Rails, Laravel, Vue Web Development: HTML5, CSS3 Database Management: SQL, MySQL, PostgreSQL Operating Systems: Windows, MacOS Version Control: Git Software Development Methodologies: Agile Developer tools: GitHub, Slack Deployment and hosting: AWS, Render, Netlify Professional: Remote pair programming, Teamwork, Mentoring I am currently seeking new opportunities as a full-stack developer and would be thrilled to connect with anyone who shares my passion for building high-quality, maintainable software solutions. Let's schedule a Zoom chat to discuss how we can work together to create something amazing. Feel free to email me at petzyrockchendi@gmail.com."