Using Paperclip within seeds.rb

假如想象 提交于 2019-12-03 10:16:52

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

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.

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