Question

Let's says I have the following entry in my seeds.rb file :

Image.create(:id => 52, :asset_file_name => "somefile.jpg", :asset_file_size => 101668, :asset_content_type => "image/jpeg", :product_id => 52)

If I seed it, it tries to process the image specified, I get this error :

No such file or directory - {file path} etc...

My images are backed up, so I don't really need to create them; but I need the record though. I can't comment the paperclip directive in my model; then it works; but I guess there might be another solution.

Is there another pattern to follow in order to accomplish it ? Or a turnaround to tell paperclip not to process the image ?

Was it helpful?

Solution

Rather than setting the asset columns directly, try leveraging paperclip and setting it as ruby File object.

Image.create({
  :id => 52, 
  :asset => File.new(Rails.root.join('path', 'to', 'somefile.jpg')),
  :product_id => 52
})

OTHER TIPS

The other answer here certainly works for most situations, but in some cases it may be better yet to provide an UploadedFile rather than a File. This more closely mimics what Paperclip would receive from a form and provides some additional functionality.

image_path = "#{Rails.root}/path/to/image_file.extension"
image_file = File.new(image_path)

Image.create(
  :id => 52,
  :product_id => 52,
  :asset => ActionDispatch::Http::UploadedFile.new(
    :filename => File.basename(image_file),
    :tempfile => image_file,
    # detect the image's mime type with MIME if you can't provide it yourself.
    :type => MIME::Types.type_for(image_path).first.content_type
  )
)

While this code is somewhat more complicated, it has the benefit of correctly interpreting Microsoft Office documents with .docx, .pptx, or .xlsx extensions which, if attached using a File object, will be uploaded as zip files.

This especially matters if your model permits Microsoft Office documents but does not allow zip files, because validations will otherwise fail and your object won't be created. It wouldn't have affected the OP's situation, but it affected mine, and so I wish to leave my solution in case anyone else needs it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top