2014-01-31 68 views
2

我正在創建一個將執行以下三件事的遷移:創建一個名爲images的表,將products表中的所有圖像轉移到新的images表中,然後從products表中刪除所有圖像列。如何創建將所有圖像從一個表格轉移到另一個表格的Rails遷移?

除傳輸圖像部分外,一切正常。沒有圖像信息傳輸。

這裏的遷移:

class CreateImages < ActiveRecord::Migration 
    def change 
    create_table :images do |t| 
     t.belongs_to :product 
     t.string :image_file_name, :image_content_type 
     t.integer :image_file_size 
     t.boolean :main, :default => false 

     t.timestamps 
    end 

    Product.all.each do |product| 
     begin 
     product.images.create(:image => product.image, :main => true) 
     rescue => e 
     logger.warn "Error while transferring images from product: #{product.name} to Images: #{e}" 
     end 
    end 

    remove_column :products, :image_file_name 
    remove_column :products, :image_content_type 
    remove_column :products, :image_file_size 
    remove_column :products, :image_updated_at 

    add_index :images, [:product_id, :main] 
    end 
end 

回答

2

你不應該一個ActiveRecord遷移內執行,如文件處理文件系統操作。這主要是因爲ActiveRecord遷移是在數據庫事務中執行的,並且如果事務文件對文件的更改不會被壓降。此外,如果您嘗試處理大量文件,則可能會遇到意外的數據庫連接超時或類似錯誤。

您必須在lib目錄中創建一個Rake任務,並在遷移完成後運行它。這樣的rake任務應該首先將文件複製到一個新的目錄,然後刪除舊的文件。你可能會覺得這篇文章有用:http://fernandomarcelo.com/2012/05/paperclip-how-to-move-existing-attachments-to-a-new-path/。這不是特定的回形針。

最後,在不同的遷移中運行remove_column語句。

class CreateImages < ActiveRecord::Migration 
    def change 
    create_table :images do |t| 
     t.belongs_to :product 
     t.string :image_file_name, :image_content_type 
     t.integer :image_file_size 
     t.boolean :main, :default => false 

     t.timestamps 
    end 
    end 
end 

在這裏手動運行您的任務。

最後,執行以下遷移。

class RemoveImagesFromProducts < ActiveRecord::Migration 

    def change 
    remove_column :products, :image_file_name 
    remove_column :products, :image_content_type 
    remove_column :products, :image_file_size 
    remove_column :products, :image_updated_at 

    add_index :images, [:product_id, :main] 
    end 
end 
+0

謝謝你的幫助提示。你知道我應該如何傳送圖像嗎? – Snubber

+0

剛剛更新了我的答案。 –

相關問題