Wednesday, 23 December 2020

Image upload by active storage

 

https://www.dailysmarty.com/posts/steps-for-using-active-storage-to-upload-files-to-s3-with-ruby-on-rails

https://github.com/jeygeethan/activestorage-backblaze

Add gem:

gem 'activestorage-backblaze'   is gem only user for backblaze ke liye hai.

gem "aws-sdk-s3", require: false


Image upload on backblaze:

backblaze:

  service: Backblaze

  bucket_name: <%= ENV['BUCKET_NAME'] %>

  bucket_id: <%= ENV['BUCKET_ID'] %>

  key_id: <%= ENV['KEY_ID'] %>

  key_token: <%= ENV['KEY_TOKEN'] %>



Run the command:

rails active_storage:install

Followed by:

rails db:migrate

 

Step 2 - Update Storage Parameters

In the config/storage.yml file, uncomment the 'amazon' configuration options. Make sure to add your region and bucket name.

Add this code config/storage.yml

amazon:

  service: S3

  access_key_id: <%= ENV['AWS_ACCESS_KEY'] %>

  secret_access_key: <%= ENV['AWS_SECRET_KEY'] %>

  region: <%= ENV['AWS_RESION'] %>

  bucket: <%= ENV['AWS_BUCKET'] %>



==============================================


In the config/environments/development.rb there should be a line that says:

config.active_storage.service = :local

And in the config/environments/production.rb you'll need to remove the line:

config.active_storage.service = :local

And add the line:

This is amazon

config.active_storage.service = :amazon

=============================================

This is backblaze

config.active_storage.service = :backblaze


=============================================


Add a model:

has_one_attached :featured_image


==============================================

Image upload form minio

Add this code config/storage.yml

minio_dev:

  service: S3

  access_key_id: <%= ENV['STORAGE_ACCESS_KEY'] %>

  secret_access_key: <%= ENV['STORAGE_SECRET_ACCESS_KEY'] %>

  region: <%= ENV['STORAGE_REGION'] %>

  bucket: <%= ENV['STORAGE_BUCKET'] %>

  endpoint: <%= ENV['Endpoint'] %>

  force_path_style: true


and config/development.rb and production.rb

config.active_storage.service = :minio_dev

---------------------------------

If in case getting this erro:
undefined method `has_one_attached' for #<Class:0x000055cfabb92460> (NoMethodError)


Add this line in application.rb

ActiveSupport.on_load(:active_record) do
  include ActiveStorage::Reflection::ActiveRecordExtensions
  ActiveRecord::Reflection.singleton_class.prepend(ActiveStorage::Reflection::ReflectionExtension)
  include ActiveStorage::Attached::Model
end
On top:


attribute :profile_image do |object|

      if object.profile_pic.attached?

        # ENV["API_BASE_URL"] + Rails.application.routes.url_helpers.rails_blob_url(object.profile_pic, only_path: true)

        object.profile_pic.service_url

      end

    end