Ruby on rails 在seeds.rb中使用回形针
假设我的Ruby on rails 在seeds.rb中使用回形针,ruby-on-rails,ruby,paperclip,seed,Ruby On Rails,Ruby,Paperclip,Seed,假设我的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
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文件
对象
Image.create({
:id => 52,
:asset => File.new(Rails.root.join('path', 'to', 'somefile.jpg')),
:product_id => 52
})
这里的另一个答案当然适用于大多数情况,但在某些情况下,提供上传文件
可能比提供文件
更好。这更接近于纸夹从表单接收的内容,并提供了一些附加功能
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文档,如果使用文件对象进行附加,这些扩展名将作为zip文件上载
如果您的模型允许使用Microsoft Office文档,但不允许使用zip文件,这一点尤其重要,因为否则验证将失败,并且不会创建对象。它不会影响OP的情况,但会影响我的情况,因此我希望留下我的解决方案,以防其他人需要它。这是处理更多文件类型的更好解决方案。这也适用于字体。我建议使用File.join
而不是插入字符串File.join(Rails.root,'path','to','somefile.jpg')