Aloha!
Rails provides Active Storage that makes it easy to attach files to records. Records as in @post object here.
Let's attach an image to a Post instance.
It's simple.
# app/models/post.rb
class Post < ApplicationRecord
# ...
has_one_attached :avatar
# has_many_attached :object for multiple attachments
end
Before we do anything we have to setup active storage in our Rails application.
Run the following commands:
rails active_storage:install
rails db:migrate
# On running these commands rails creates and uses three tables :active_storage_blobs, :active_storage_variant_records and :active_storage_attachments which creates a record_id for every attached files by referring to the ***Class Name*** and it's instances.
For further reference: edgeguides.rubyonrails.org/active_storage_o..
Now we can simply attach an avatar image to @post by adding file_field to the form:
# app/views/posts/new.html.erb
# ...
<% = form.file_field :avatar %>
# ...
You are displayed a file upload option in the webpage where you can upload it to the server.
What if you want to upload these attachments to a cloud service and not locally?
# config/environments/development.rb
config.active_storage.service = :local
# Change from :local to :amazon or :google or whatever service you decide to use.
# We will use Amazon's Simple Storage Service [AWS-S3]
config.active_storage.service = :amazon
To enable our cloud to store files uploaded from our app we have to set up a few things in the Amazon Console to get it up and running.
Since I've already lost my focus here I am writing it tomorrow.
If I remember...
Please remind me at:
Thank you!
Love,
M.
liked_the_post == true ? comment and share : comment and share