16

假设我的seeds.rb文件中有以下条目:

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

如果我播种它,它会尝试处理指定的图像,我会收到此错误:

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

我的图像已备份,因此我真的不需要创建它们;但我需要记录。我无法在我的模型中评论回形针指令;然后它起作用了;但我想可能还有另一种解决方案。

为了完成它,是否有另一种模式可以遵循?还是告诉回形针不要处理图像的转机?

4

2 回答 2

41

与其直接设置资产列,不如尝试利用回形针并将其设置为 rubyFile​​ 对象。

Image.create({
  :id => 52, 
  :asset => File.new(Rails.root.join('path', 'to', 'somefile.jpg')),
  :product_id => 52
})
于 2013-02-25T03:27:24.620 回答
4

这里的另一个答案当然适用于大多数情况,但在某些情况下,提供 aUploadedFile而不是 a可能会更好File。这更接近地模仿了 Paperclip 从表单接收的内容并提供了一些额外的功能。

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

虽然此代码稍微复杂一些,但它的好处是可以正确解释带有 .docx、.pptx 或 .xlsx 扩展名的 Microsoft Office 文档,如果使用 File 对象附加这些文件,它们将作为 zip 文件上传。

如果您的模型允许 Microsoft Office 文档但不允许 zip 文件,这一点尤其重要,因为否则验证将失败并且您的对象将不会被创建。它不会影响 OP 的情况,但会影响我的情况,因此我希望保留我的解决方案以防其他人需要它。

于 2015-09-30T01:57:58.650 回答