Using Paperclip within seeds.rb
Asked Answered
C

2

16

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 ?

Complication answered 24/2, 2013 at 15:15 Comment(0)
I
41

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
})
Intercalation answered 25/2, 2013 at 3:27 Comment(1)
I recommend use File.join instead of interpolating string. File.join(Rails.root, 'path', 'to', 'somefile.jpg')Workman
S
4

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.

Sideboard answered 30/9, 2015 at 1:57 Comment(1)
this is a better solution to handle more file types. this works with fonts as well.Kalmuck

© 2022 - 2024 — McMap. All rights reserved.