简体   繁体   English

狂欢::Image.create! - 无法创建

[英]Spree::Image.create! - can't create

When I create an application and rake task, cannot run 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当我创建应用程序和 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

What kind of information is missing ?缺少什么样的信息? Do I need to prescribe additional parameters separately And what kind of validation I can't get through ?我需要单独规定额外的参数吗?我无法通过什么样的验证? ? ? If check the path manually to the picture, through the rails console, the picture can be seen.如果手动查看图片的路径,通过rails控制台,可以看到图片。

My code我的代码

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

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

need write on需要写上

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

That's all and it's working这就是全部,它正在起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM