Link an object to a pre-existing S3 file using Paperclip

I have a file already in S3 that I would like to link to an existing instance of the Asset model.

Here is the model:

class Asset < ActiveRecord::Base
  attr_accessible(:attachment_content_type, :attachment_file_name,
                 :attachment_file_size, :attachment_updated_at, :attachment)

  has_attached_file :attachment, {
    storage: :s3,
    s3_credentials: {
      access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    },
    convert_options: { all: '-auto-orient' },
    url: ':s3_alias_url',
    s3_host_alias: ENV['S3_HOST_ALIAS'],
    path: ":class/:attachment/:id_partition/:style/:filename",
    bucket: ENV['S3_BUCKET_NAME'],
    s3_protocol: 'https'
  }
end

Let's say the path assets/attachments/000/111/file.png, and the instance Assetthat I want to associate with the file is Asset. Turning to source , I tried:

options = {
    storage: :s3,
    s3_credentials: {
      access_key_id: ENV['AWS_ACCESS_KEY_ID'],
      secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    },
    convert_options: { all: '-auto-orient' },
    url: ':s3_alias_url',
    s3_host_alias: ENV['S3_HOST_ALIAS'],
    path: "assets/attachments/000/111/file.png",
    bucket: ENV['S3_BUCKET_NAME'],
    s3_protocol: 'https'
  }
# The above is identical to the options given in the model, except for the path

Paperclip::Attachment.new("file.png", asset, options).save

As far as I can tell, this has no effect on Asset. I can not install asset.attachment.pathmanually.

Other SO questions do not seem to address this specifically. " Bonded images are not saved in the path I set ," Paperclip and Amazon S3 how to make paths? "etc. includes setting up a model that is already working fine.

Anyone have any ideas to suggest?

+4
2

, S3 File, @oregontrail256. Fog gem.

s3 = Fog::Storage.new(
        :provider => 'AWS',
        :aws_access_key_id => ENV['AWS_ACCESS_KEY_ID'],
        :aws_secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
      )

directory = s3.directories.get(ENV['S3_BUCKET_NAME'])
fog_file = directory.files.get(path)

file = File.open("temp", "wb")
file.write(fog_file.body)
asset.attachment = file
asset.save
file.close
+2

copy_to_local_file(), . :

file_name = "temp_file"
asset1.attachment.copy_to_local_file(:style, file_name)
file = File.open(file_name)
asset2.attachment = file
file.close
asset2.save!

1, , 2 . , , .

: Paperclip

+1

Source: https://habr.com/ru/post/1539692/


All Articles