【问题标题】:Using Paperclip within seeds.rb在种子.rb 中使用回形针
【发布时间】:2026-02-15 13:50:02
【问题描述】:

假设我的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...

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

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

【问题讨论】:

    标签: ruby-on-rails ruby paperclip seed


    【解决方案1】:

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

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

    【讨论】:

    • 我建议使用File.join 而不是插入字符串。 File.join(Rails.root, 'path', 'to', 'somefile.jpg')
    【解决方案2】:

    这里的另一个答案当然适用于大多数情况,但在某些情况下,提供UploadedFile 而不是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 的情况,但会影响我的情况,因此我希望保留我的解决方案以防其他人需要它。

    【讨论】:

    • 这是处理更多文件类型的更好解决方案。这也适用于字体。