在seeds.rb中使用Paperclip

我们说我的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... 

我的图像备份,所以我真的不需要创建它们; 但我需要记录。 我不能在我的模型中评论paperclip指令; 然后它起作用; 但我想可能还有另一种解决方案。

是否还有其他模式可以实现它? 或者告诉回形针不要处理图像?

不要直接设置资产列,而是尝试利用paperclip并将其设置为ruby File对象。

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

这里的另一个答案肯定适用于大多数情况,但在某些情况下,提供UploadedFile而不是File可能更好。 这更接近于模仿Paperclip从表单中获得的内容并提供一些额外的function。

 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文件,这尤其重要,因为validation将失败并且您的对象将不会被创建。 它不会影响OP的情况,但它会影响我的,所以我希望留下我的解决方案以防其他人需要它。