When I was planning for my Flatiron School rails project I decided to go with a simple e-commerce app. As I was planning my project it was apparent that at some point I would have to give my app the ability to upload and store images cause no e-commerce app will thrive without a way to showcase it’s products. Thus came in Active Storage. Active Storage is Active record’s own image processing system that supports storing and processing image either locally or through a third party cloud storage services like Amazon S3 or Google cloud storage.
I decided to use my local storage for my app in development phase. Active record has an elaborated documentation on how to integrate Active storage to a rails app. It’s pretty straight forward.
For my app, first I installed Active Storage to my existing rails app. In the root directory of my app I ran this code in my terminal.
rails active_storage:install
Then, ran the migrations.
rails db:migrate
This created the migrations needed for the image upload ability and added these to table to my schema.
After that in my model file that would be associated with images, I had to declare it like this.
If the model object had to be associated with multiple images I would declare it as has_many_attached : images.
After this I went to my config/environments/development.rb and told active storage to use :local as storage.
config.active_storage.service = :local
After that in the related controller I had to permit :image for the params.
In the corresponding views I created a file field for option to upload an image.
And in the show page just called the associated object with .image to view the image. If anyone wants to resize the image in a view, a active record variant is needed. I’ve used the “image_processing” gem to resize my images to thumbnail size. It’s simple. Just add
and bundle install. After that you can declare the size of the image directly in the view or in the model file whichever suits you better.
And that’s it. That’s how I integrated a simple image upload/showcase to my app. Hope it helps you and if there are any advises or an easier way to do this, feel free to comment. Thank you.