【问题标题】:Rails rake file and uploading multiple image assetsRails rake 文件和上传多个图像资产
【发布时间】:2014-03-07 01:02:36
【问题描述】:

我正在使用 rake 文件上传网站上的现有内容(从 CSV 文件和图像文件夹填充)。此内容由列表组成,其中包含各种详细信息、一个上传的“图片”和最多 5 个额外上传的“资产”(照片)。

我有一个包含一个图像的列表模型,以及一个资产模型,其中最多包含 5 个其他图像/资产。资产属于一个listing,一个listing有很多assets。

从网络表单创建新列表时,一切正常,我的控制器如下所示:

  def new
    @listing = current_user.listings.build
    5.times { @listing.assets.build}
  end

图像/资产由回形针和 imagemagick 处理

rake 文件适用于除附加资产(照片)之外的所有组件。我可以上传附加到同一模型的单个图像:

image = File.open(Rails.root.join('location/', 'image_name'))

但是我什至无法上传单个资产:

asset = File.open(Rails.root.join('location/', 'asset_name'))

我当前用于上传内容的 rake 文件如下所示:

     CSV.foreach(file, :headers => true) do |row|
        puts "[DEBUG] uploading new listing"
        image = File.open(Rails.root.join('sampleimages/', row[6])) #this is working properly to upload the single image that's attached to the listing model
        assets = File.open(Rails.root.join('sampleimages/', row[7])) #this is not working, even when I'm only trying to attach one of the possible five assets   
        User.last.listings.create!(assets: assets, image: image, listingname: row[20], provider_phone: row[13], provider_email: row[14], blah blah)
      end

运行 rake:populate: 时,我的终端出现以下错误:

Asset(#70364324499020) expected, got File(#70364281853460)

知道我哪里出错了吗?实际上,我需要打开 5 个文件,并将它们保存为“资产”。

解决方案:

问题是我试图通过列表创建过程附加图像资产:

User.last.listings.create!(attribute1: row[1], attribute2: row[2].....)

但由于我的资产模型与列表模型是分开的,我只需要使用以下方法:

asset1 = File.open(Rails.root.join('sampleimages/', row[7])) unless row[7].nil?
asset2 = File.open(Rails.root.join('sampleimages/', row[8])) unless row[8].nil?
asset3 = File.open(Rails.root.join('sampleimages/', row[9])) unless row[9].nil?
asset4 = File.open(Rails.root.join('sampleimages/', row[10])) unless row[10].nil?
asset5 = File.open(Rails.root.join('sampleimages/', row[11])) unless row[11].nil?
Asset.create!(asset: asset1, listing_id: User.last.listings.last.id) unless row[7].nil?
Asset.create!(asset: asset2, listing_id: User.last.listings.last.id) unless row[8].nil?
Asset.create!(asset: asset3, listing_id: User.last.listings.last.id) unless row[9].nil?
Asset.create!(asset: asset4, listing_id: User.last.listings.last.id) unless row[10].nil?
Asset.create!(asset: asset5, listing_id: User.last.listings.last.id) unless row[11].nil?

希望有帮助

【问题讨论】:

    标签: ruby-on-rails imagemagick paperclip rake-task


    【解决方案1】:

    用我的解决方案更新了问题

    【讨论】:

      猜你喜欢
      • 2018-08-11
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-28
      相关资源
      最近更新 更多