【问题标题】:Spree::Image.create! - can't create狂欢::Image.create! - 无法创建
【发布时间】:2018-08-14 13:13:51
【问题描述】:

当我创建应用程序和 rake 任务时,无法运行 Spree:: Image.create!(attachment: File.open (Rails.root + 'app/assets/images/bottle / 1.jpeg'), viewable: product) - ActiveRecord error:: RecordInvalid: Validation failed: Attachment must be present

缺少哪些信息?我需要单独规定额外的参数吗?我无法通过什么样的验证? ? 如果手动查看图片的路径,通过rails控制台可以看到图片。

我的代码

namespace :give_me do
  desc 'Load 18 products in database'
  task products: :environment do
    19.times do |i|
      kinds_rand = File.new(Rails.root + 'db/mock_data/kinds.md').readlines.sample
      regions_rand = File.new(Rails.root + 'db/mock_data/regions.md').readlines.sample
      names_rand = File.new(Rails.root + 'db/mock_data/names.md').readlines.sample
      product = Spree::Product.create!(
        name: name = names_rand.chomp,
        description: "New wine product #{i + 1}",
        available_on: Time.zone.now - 1.day,
        shipping_category: Spree::ShippingCategory.first,
        meta_description: 'Wine, is the best drink in the world',
        meta_keywords: %w[wine drink alcohol bottle expensive drink'],
        meta_title: name,
        price: rand(50..800),
        sku: rand(1_000_000..1_999_999),
        year: rand(1960..2005),
        region: regions_rand.chomp,
        alcohol_percentage: rand(5..15),
        wine_kind: kinds_rand.chomp
      )
      Spree::Image.create!(
          attachment: File.open(Rails.root + 'app/assets/images/bottle/1.jpeg'), viewable: product
      )
    end
    puts "Here are your products"
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby spree


    【解决方案1】:

    好的,我找到了决定。 Spree::Image.create!(附件:File.open(Rails.root + 'app/assets/images/bottle/1.jpeg'),可见:产品)

    需要写

    file_image = File.open(Rails.root.join('app', 'assets', 'images', '1.jpg'))
    image = Spree::Image.create!(attachment: { io: file_image, filename: "#{rand(1..20)}.jpg" })
    product.images << image
    

    就是这样,它正在工作

    【讨论】:

    • 那里面的file_image是什么?
    • @Eric 抱歉,我忘了添加 file_image 变量。 file_image 是文件的路径
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多