2013-02-24 39 views
11

讓我們說,我有我的seeds.rb文件中的以下條目: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... 

我的圖像已備份,所以我不需要創建它們;但我需要記錄。我無法評論我的模型中的回形針指令;那麼它的工作;但我想可能有另一種解決方案。

爲了實現它,還有其他的模式嗎?或者讓回形針告訴回形針不要處理圖像?

回答

37

不是直接設置資產列,而是嘗試利用回形針並將其設置爲ruby File對象。

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

我推薦使用'File.join'而不是內插字符串。 'File.join(Rails.root,'path','to','somefile.jpg')' – Aleksey 2016-07-06 17:27:12

1

對方回答肯定在這裏工作在大多數情況下,但在某些情況下,它可能會更好,但提供一個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文檔的好處文件。

如果您的模型允許Microsoft Office文檔但不允許使用zip文件,那麼這尤其重要,否則驗證將失敗並且您的對象將不會創建。它不會影響OP的情況,但它影響到我的,所以我希望離開我的解決方案,以防其他人需要它。

+1

這是更好的解決方案來處理更多的文件類型。這也適用於字體。 – 2016-05-13 07:44:56