我'm trying to import a CSV file to my Rails app that'使用CarrierWave来处理文件上传 . 我正在使用 CSV
gem并通过种子数据填充Rails数据库 .
我遇到的问题是导入没有填充数据库的图像字段 . image列是一个包含文件名的字符串,例如 . “这 - 是 - 我 - 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文件名的字符串 .
提前致谢 .
1 回答
你不能使用
image=
方法;这是一个CarrierWave方法(重载ActiveRecord),你在尝试直接设置字符串时会误用它 .你可以改用write_attribute
这内部是ActiveRecord在其
image=
方法中使用的内容 .