用载波上传播种文件,铁路3
-
29-09-2019 - |
题
我正在尝试使用CarrierWave在Rails 3中使用图像播种数据库,但是我尝试的任何事情似乎都没有手工上传它们。
pi = ProductImage.new(:product => product)
pi.image = File.open(File.join(Rails.root, 'test.jpg'))
pi.store_image! # tried with and without this
product.product_images << pi
product.save!
有人知道如何完全使用载体波播种吗?
解决方案
事实证明,载波的文档略有错误。有更多最新的代码 在该项目的GitHub存储库中的README中.
简而言之:
pi = ProductImage.create!(:product => product)
pi.image.store!(File.open(File.join(Rails.root, 'test.jpg')))
product.product_images << pi
product.save!
其他提示
只要使用Mount_uploader方法将上传器安装到型号上,您就可以使用相关的开放方法用载波播种模型。这将是实现同一件事的一种更简洁的方法。就我而言,我是从URL播种的:
Game.create([
{
:title => "Title",
:uuid_old => "1e5e5822-28a1-11e0-91fa-0800200c9a66",
:link_href => "link_href",
:icon => open("http://feed.namespace.com/icon/lcgol.png"),
:updated_at => "2011-01-25 16:38:46",
:platforms => Platform.where("name = 'iPhone'"),
:summary => "Blah, blah, blah...",
:feed_position => 0,
:languages => Language.where("code = 'de'"),
:tags => Tag.where(:name => ['LCGOL', 'TR', 'action'])
},
{...
这是我将我的一个项目之一纳入Seed.RB文件中的示例脚本。我确定它可以改进,但提供了一个很好的示例。
我提取的所有资产都存储在应用程序/资产/图像中,并且它们的名称与我的信息对象的名称匹配(在我用下划线替换空格并倒置名称之后)。
是的,听起来确实很低,但是除了将这些资产放在FTP某个地方外,它是我找到的远程服务器的最佳解决方案,可以使用CarrierWave和Fog将文件直接上传到S3。
我的信息模型有一个 has_one
与画廊模型的关联,该模型具有 has_many
与照片模型的关联。载波上传器安装在该模型的“文件”(字符串)列上。
Info.all.each do |info|
info_name = info.name.downcase.gsub(' ', '_')
directory = File.join(Rails.root, "app/assets/images/infos/stock/#{info_name}")
# making sure the directory for this service exists
if File.directory?(directory)
gallery = info.create_gallery
Dir.foreach(directory) do |item|
next if item == '.' or item == '..'
# do work on real items
image = Photo.create!(gallery_id: gallery.id)
image.file.store!(File.open(File.join(directory, item)))
gallery.photos << image
end
info.save!
end
end
这对我来说是完美无缺的,但是理想情况下,我不必打包要在资产文件夹中上传到S3的文件。我对建议和改进不仅仅是开放的。
所有内容都在文档中: https://github.com/carrierwaveuploader/carrierwave/wiki/how-to:-phe :-%22upload%22-from-a-local-file
restaurant = Restaurant.create!(name: "McDonald's")
restaurant.logo = Rails.root.join("db/images/mcdonalds_logo.png").open
restaurant.save!
以@Joseph Jaber的评论为基础,这为我造成了待遇:
下面的代码在 seeds.rb
20.times do
User.create!(
name: "John Smith",
email: "john@gmail.com",
remote_avatar_url: (Faker::Avatar.image)
)
end
这将创建20个用户,并为每个用户提供不同的头像图像。
我已经使用了伪造的宝石来生成数据,但全部 Faker::Avatar.image
确实是返回标准URL,因此您可以使用您选择的任何URL。
上面的示例假设用户模型属性存储在哪里,称为 avatar
如果属性称为图像,您会这样写:
remote_image_url: (Faker::Avatar.image)
对我来说最简单的解决方案是:
- 评论模型中的mount_uploader线
- 播种数据
- 删除模型中的行