Instantiate image in rails 3.1 app then upload to S3 with paperclip
I'm creating a barcode .png in a callback using the Barby gem:
Isbn.rb:
before_save :barcode
def barcode
barcode = Barby::Bookland.new(self.productidentifier_idvalue)
my_bc = Barcodeimg.new(:isbn_id => self.id)
my_bc.image = File.open("#{self.productidentifier_idvalue}-barcode.png", 'w') do |f|
f.write barcode.to_png
end
my_bc.save!
end
Then I'm hoping to upload it directly to S3 via paperclip: here's the Barcodeimg.rb model:
require 'open-uri'
require "aws/s3"
class Barcodeimg < ActiveRecord::Base
has_attached_file :image,
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:s3_protocol => "https",
:path => ":class/:id/:basename_:style.:extension",
:bucket => "bucketname",
:url => ":s3_eu_url"
end
I know the credentials work as I'm using the exact same settings in another model. Any idea what I'm doing wrong? A new Barcodeimg instance is being saved, but without the attachment. There are no error messages - just no image appearing on S3! From the stack trace:
SQL (1.8ms) INSERT INTO "barcodei开发者_运维百科mgs" ( "created_at", "image_content_type", "image_file_name", "image_file_size", "image_remote_url", "isbn_id", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ["created_at", Tue, 30 Aug 2011 20:26:20 UTC +00:00], ["image_content_type", nil], ["image_file_name", nil], ["image_file_size", nil], ["image_remote_url", nil], ["isbn_id", 7128], ["updated_at", Tue, 30 Aug 2011 20:26:20 UTC +00:00], ["user_id", nil]]
[paperclip] Saving attachments.
File.open will return the result of the block. Which means you're writing the length of the file to your attachment.
I would replace the block with:
f = File.open("#{self.productidentifier_idvalue}-barcode.png", 'w+')
f.write barcode.to_png
my_bc.image = f
Another problem could be the permissions of the current directory. Do you have the rights to write there?
精彩评论