0

I'm trying to import a CSV file to my Rails app that's using CarrierWave to handle file uploads. I'm using the CSV gem and populating the Rails database via a seed data.

The issue I'm having is the import doesn't populate the image field of the database. The image column is a string that holds the filename eg. 'this-is-my-photo.jpg'.

I have a database table that has the following columns:

# 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

The results of 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

Everything but the image column was populated.

I was wondering if anyone can give me tips on how to go about resolving this import/population issue. Has anyone experienced this problem before and is it because of the the filename type (eg. .jpg)?

Also, I have the same problem when restoring my user model that has an avatar column which is a string that holds the CarrierWave filename.

Thanks in advance.

4

1 回答 1

2

您不能使用该image=方法; 这是您在尝试直接设置字符串时误用的 CarrierWave 方法(重载 ActiveRecord) 。

您可以改为使用write_attribute

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

这在内部是 ActiveRecord 在其image=方法中使用的。

于 2012-11-03T12:47:22.953 回答