'Active Storage Rails 6 API unable to insert to active_storage_attachments table

I am creating API endpoint for active storage with reactjs. My upload controller is as follows: The code belows execute:

  1. insert blob object in active_storage_blob - ok

  2. Upload file to designated path in storage - ok

  3. does not insert active_storage_attachments (polymorphic relation) I already add has_one_attached :photo

    class Api::V1::Activestorage::DirectUploadsController < 
          ActiveStorage::DirectUploadsController
    
          skip_before_action :verify_authenticity_token
    
         def create
            blob = ActiveStorage::Blob.create_before_direct_upload!(**blob_args)
            render json: direct_upload_json(blob)
         end
    
        private
    
        def blob_args
         params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type, metadata: {}).to_h.symbolize_keys
        end
    
       def direct_upload_json(blob)
          blob.as_json(root: false, methods: :signed_id).merge(direct_upload: {
           url: blob.service_url_for_direct_upload,
           headers: blob.service_headers_for_direct_upload
         })
       end
     end     
    

all are ok except for this active_storage_attachment table are not inserted. Hope someone can help. Thanks all



Solution 1:[1]

I add a new method for attachment this is my refactor code. Hope this will help.

class Api::V1::UploadController < ActiveStorage::DirectUploadsController

 skip_before_action :verify_authenticity_token

 def create
     blob = ActiveStorage::Blob.create_before_direct_upload!(blob_args)
     render json: direct_upload_json(blob)
 end

 def attached_create
   ActiveStorage::Attachment.create(params_attached) #from react axios pass params
 end

 private

 def params_attached
    params.require(:attachment).permit(:name, :record_type, :record_id, :blob_id)
 end

 def blob_args
    params.require(:blob).permit(:filename, :byte_size, :checksum, :content_type, metadata: {}).to_h.symbolize_keys
 end

def direct_upload_json(blob)
    blob.as_json(root: false, methods: :signed_id).merge(service_url: url_for(blob)).merge(direct_upload: {
      url: blob.service_url_for_direct_upload,
      headers: blob.service_headers_for_direct_upload
    })
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lyndon Abesamis