私はこの同じ問題に数回遭遇しました。私がそれを解決した方法は、Image
モデルとTempImage
モデルを継承するモデルの2つのモデルを作成することでしたImage
。これには、テーブルにtype
列が必要です。モデルは画像をローカルに保存し、モデルから直接アクセスしてImage
再保存すると、 Amazon S3であるモデルで定義されているものに従います。TempImage
Image
Image
例:
# Will save in the database as a TempImage inside the Image table
temp = TempImage.create(:asset => File.new('some_path', 'r'))
# When you find it again through the Image model, it bypasses the type column
# so next time you save it, it is saved as an Image.
amazon = Image.find(temp.id)
amazon.save!
これが私の遅れた仕事です:
class MoveToS3Job < Struct.new(:temp_revision_id)
def perform
upload = Image.find(temp_revision_id)
temp_path = File.expand_path("tmp/uploads/#{upload.asset_file_name}", Rails.root)
upload.asset = File.new(temp_path, 'r')
upload.save!
if File.exists?(temp_path) && !File.directory?(temp_path)
File.delete(temp_path)
end
rescue ActiveRecord::RecordNotFound
# If the record wasn't found, do some sort of
# error report, but don't keep it in the queue.
end
end
TempImage
モデルは次のとおりです。
class TempImage < Image
has_attached_file :asset, {
:path => ":rails_root/tmp/uploads/:basename_:updated_at.:extension"
}
end
次に、元のImage
モデル:
class Image < ActiveRecord::Base
# Validations
validates :asset, :presence => true
# Paperclip
has_attached_file :asset, :styles => {
:preview => ['100x100#', :png],
:thumb => ['50x50#', :png]
},
:default_style => :thumb,
:storage => :s3,
:bucket => 'bucket-name',
:s3_credentials => File.expand_path('config/s3.yml', Rails.root),
:path => "photos/:id_partition/:style.:extension"
end
後処理はバックグラウンドで行われるため、元のImage
モデルには常に後処理が含まれている必要があります。
いつでもいくつかのメソッドを上書きして少しきれいにすることができますが、これにより、それがどのように機能し、何をする必要があるかについてのより良いアイデアが得られるため、希望どおりに機能させることができます.