使用 CarrierWave、Rails 3 播种文件上传

发布于 2024-09-27 15:57:18 字数 330 浏览 4 评论 0原文

我正在尝试使用 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!

有人知道如何使用 CarrierWave 进行播种吗?

I'm trying to seed a database in Rails 3 with images using CarrierWave, however nothing I try seems to work short of having to upload them all by hand.

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!

Anybody know how to seed using CarrierWave at all?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

日记撕了你也走了 2024-10-04 15:57:18

事实证明 CarrierWave 的文档略有错误。 该项目的 GitHub 存储库的自述文件中有一段更新的代码。

简而言之:

pi = ProductImage.create!(:product => product)
pi.image.store!(File.open(File.join(Rails.root, 'test.jpg')))
product.product_images << pi
product.save!

Turns out the documentation for CarrierWave is slightly wrong. There is a more up to date piece of code in the README at the GitHub repository for the project.

In a nutshell, though:

pi = ProductImage.create!(:product => product)
pi.image.store!(File.open(File.join(Rails.root, 'test.jpg')))
product.product_images << pi
product.save!
瞳孔里扚悲伤 2024-10-04 15:57:18

只要使用 mount_uploader 方法将您的上传器安装到您的模型上,您就可以使用相关的 open 方法为您的模型播种载波。这将是实现相同目标的更简洁的方法。就我而言,我从 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'])
},
{...

So long as your uploader is mounted to your model, using the mount_uploader method, you can seed your models with carrierwave using the relevant open method. This would be a more concise way of achieving the same thing. In my case I'm seeding from a 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'])
},
{...
柳絮泡泡 2024-10-04 15:57:18

基于 @joseph jaber 的评论,这对我来说是一种享受:

下面的代码应该在 seeds.rb 中,

20.times do
        User.create!(
            name: "John Smith",
            email: "[email protected]",
            remote_avatar_url: (Faker::Avatar.image)
        )
    end

这将创建 20 个用户,并为每个用户提供不同的头像图像。

我已经使用 faker gem 来生成数据,但所有 Faker::Avatar.image 所做的只是返回一个标准 url,因此您可以使用您选择的任何 url。

上面的示例假设您存储图像的 User models 属性称为 avatar

如果该属性称为 image,您将像这样编写:

remote_image_url: (Faker::Avatar.image)< /代码>

Building on @joseph jaber's comment this worked a treat for me:

The code below shoud be in seeds.rb

20.times do
        User.create!(
            name: "John Smith",
            email: "[email protected]",
            remote_avatar_url: (Faker::Avatar.image)
        )
    end

This will create 20 users and give each one a different avatar image.

I have used the faker gem to generate the data but all Faker::Avatar.image does is return a standard url, so you could use any url of your choice.

The above example assumes that the User models attribute where you store you images is called avatar

If the attribute was called image you would write like this:

remote_image_url: (Faker::Avatar.image)

那支青花 2024-10-04 15:57:18

下面是我将一个示例脚本合并到我的一个项目的 Seed.rb 文件中。
我确信它可以改进,但它提供了一个很好的工作示例。

我要提取的所有资产都存储在应用程序/资产/图像中,并且它们的名称与我的 Info 对象的名称匹配(在我用下划线替换空格并将名称小写之后)。

是的,这听起来确实效率低下,但除了将这些资产放在 FTP 上的某个地方之外,这是我为远程服务器找到的最佳解决方案,能够使用 Carrierwave 和 Fog 将文件直接上传到 S3。

我的 Info 模型与 Gallery 模型具有 has_one 关联,而 Gallery 模型与 Photo 模型具有 has_many 关联。 Carrierwave 上传器安装在该模型的“文件”(字符串)列上。

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 的文件打包到资产文件夹中。我非常乐意接受建议和建议。改进。

Here's an example script I incorporated into a seed.rb file for one of my projects.
I'm sure it can be improved but it provides a good working example.

All the assets I'm pulling are stored within the app/assets/images and they have names matching the names of my Info objects (after I replace spaces with underscores and downcase the names).

Yes it does sound inefficient, but apart from putting those assets on an FTP somehwhere, it's the best solution I found for my remote server to be able to upload the files straight to S3 using Carrierwave and Fog.

My Info model has a has_one association to a Gallery model, which has a has_many association to a Photo model. The Carrierwave uploader is mounted on the 'file' (string) column of that model.

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

This works flawlessly for me, but ideally I wouldn't have to package the files that I'm uploading to S3 within the assets folder. I'm more than open to suggestions & improvements.

吻安 2024-10-04 15:57:18

这一切都在文档中: https://github.com/rierwaveuploader/carrierwave/wiki/How-to:-%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!

It's all in the documentation: https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-%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!
多孤肩上扛 2024-10-04 15:57:18

对我来说最简单的解决方案是:

  1. 注释掉模型中的 mount_uploader 行
  2. 播种数据
  3. 取消注释模型中的行

The easiest solution for me was:

  1. Comment-out the mount_uploader line in the model
  2. Seed the data
  3. Uncomment the line in the model
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文