2012-11-03 54 views
0

我試圖將CSV文件導入到使用CarrierWave處理文件上傳的Rails應用程序。我正在使用CSV gem並通過種子數據填充Rails數據庫。在Rails中導入具有文件名作爲字符串的CSV的問題

我遇到的問題是導入不會填充數據庫的圖像字段。圖像列是保存文件名的字符串,例如。 「這 - 是 - 我 - photo.jpg」。

我有以下幾列數據庫表:

# ProductImage model, product_image table 

id |  image |  tile  | product_id | created_at | updated_at 
-------------------------------------------------------------------------- 
1 | image-1.jpg | Big shoe  |  11  | 2012-08-01 | 2012-08-01 
2 | 1-photo.png | Small hat  |  12  | 2012-08-01 | 2012-08-01 
3 | jeansb1.gif | Ankle socks |  13  | 2012-08-01 | 2012-08-01 


# Import product_image table backup 
CSV.foreach(Rails.root.join("db/seeds/product_image.csv"), headers: true) do |row| 
    ProductImage.create! do |product_image| 
    product_image.id = row[0] 
    product_image.title = row[1] 
    product_image.image = row[2] 
    product_image.product_id = row[3] 
    end 
end 

db:seed

# ProductImage model, product_image table after population of seed data 

id |  image |  tile  | product_id | created_at | updated_at 
-------------------------------------------------------------------------- 
1 |    | Big shoe  |  11  | 2012-11-01 | 2012-11-01 
2 |    | Small hat  |  12  | 2012-11-01 | 2012-11-01 
3 |    | Ankle socks |  13  | 2012-11-01 | 2012-11-01 

一切的結果,但被填充image列。

我想知道是否有人能給我如何去解決這個導入/人口問題的技巧。有沒有人遇到過這個問題,是因爲文件名類型(例如.jpg)?

此外,恢復有一個avatar列這是保存CarrierWave文件名的字符串我的用戶模型時,我也有同樣的問題。

在此先感謝。

回答

2

您不能使用image=方法;這是一種CarrierWave方法(重載ActiveRecord的)當您嘗試直接設置字符串時,您正在濫用。

您可以改用write_attribute

product_image.raw_write_attribute(:image, row[2]) 

這是內部ActiveRecord的東西里面使用它的方法image=

+0

嘿Deefour,謝謝你花時間回覆。我有一個小問題與write_attribute,我得到一個錯誤:要求#私有方法'write_attribute

+0

我所用的方法raw_write_attribute來填充image列。再次感謝Deefour的洞察力。好東西。 –

+0

對,對你有好處;我會更新我的答案以反映該公共別名。 – deefour