Using Paperclip within seeds.rb

会有一股神秘感。 提交于 2019-12-09 08:07:12

问题


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 ?


回答1:


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
})



回答2:


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.



来源:https://stackoverflow.com/questions/15053138/using-paperclip-within-seeds-rb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!