簡體   English   中英

使用CarrierWave,Rails 3上傳種子文件

[英]Seeding file uploads with CarrierWave, Rails 3

我正在嘗試使用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種子嗎?

原來CarrierWave的文檔有點不對勁。 在項目的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方法將上傳器安裝到模型上,就可以使用相關的open方法使用carrierwave為模型設定種子。 這將是實現同樣事情的更簡潔方式。 在我的情況下,我從一個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文件中。 我確信它可以改進,但它提供了一個很好的工作示例。

我所拉的所有資產都存儲在app / assets / images中,並且它們的名稱與我的Info對象的名稱相匹配(在我用下划線替換空格並將名稱縮小后)。

是的,它聽起來效率低下,但除了將這些資產放在FTP的某個地方之外,這是我發現遠程服務器能夠使用Carrierwave和Fog將文件直接上傳到S3的最佳解決方案。

我的Info模型與Gallery模型具有has_one關聯,該模型與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的文件打包到assets文件夾中。 我對建議和改進持開放態度。

這些都在文檔中: 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!

基於@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 gem生成數據,但所有Faker::Avatar.image都會返回一個標准網址,因此您可以使用您選擇的任何網址。

上面的示例假定您存儲圖像的用戶模型屬性稱為avatar

如果屬性被稱為圖像,你會這樣寫:

remote_image_url: (Faker::Avatar.image)

對我來說最簡單的解決方案是:

  1. 注釋掉模型中的mount_uploader行
  2. 種子數據
  3. 取消注釋模型中的行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM