Active Storage, made easy
Active storage has a bad reputation with a lot of developers I know. They say it is confusing and a pain in the you know what. I am here to help you through the basics of Active Storage on Rails.
First off you need to upgrade your Rails to at least 5.2 or higher. Just remember the higher the version, the more you can do with Active Storage. For the basics you only need 5.2 though. To install Active Storage first I need to explain what it is. It adds two tables to your database that holds pictures and images for your convenience. To install it into your application you need to run this code in your terminal.
This will automatically add these two tables into your database without you doing anything except running rake db:migrate. This will create two tables, that has the blobs and one that has the attachments. The blobs have the main image and the attachments has all the data that surround that image.
Incorporating Active Storage is quite easy. It easily creates all the associations for you so you don’t have to create new migrations every time you need to upload different images. To create these associations you only need to supply one line of code.
Add this line of code to any model class in your database and you automatically associate an instance of that class with an instance in the Active Storage tables. Now you can call an instance.avatar and it will show your image on that page.
Now you might be wondering how does the users of my site upload their own images. Well it is the same as creating any other form in your site. I personally used form_with but form_tag and form_for should work. Here is my example:
Using file_field will create a place for your users to upload their own images. Now the images come in all shapes and sizes so you will have to have some code that will resize and not break your website. You can do this with the minimagick gem or with css/bootstrap code. And that is the basics of Active Storage.