使用活动存储将 seed.rb 文件中的图像附加到 rails

Attach images in seed.rb file in rails using active storage

我有一个名为 vehicles 的 class,它可以附有图像。如果 vehicles.rb 文件中没有上传其他图片,我会显示默认图片。

我想在 seed.rb 文件中包含图片,这样我就不必手动上传所有图片。这可能吗?

非常感谢帮助。

这是我的 vehicle.rb:

class Vehicle < ApplicationRecord
  belongs_to :make
  belongs_to :model
  accepts_nested_attributes_for :make
  accepts_nested_attributes_for :model
  has_one_attached :image

  after_commit :add_default_image, on: %i[create update]

  def add_default_image
    unless image.attached?
      image.attach(
        io: File.open(Rails.root.join('app', 'assets', 'images', 'no_image_available.jpg')),
        filename: 'no_image_available.jpg', content_type: 'image/jpg'
      )
    end
  end
end

这是我在种子文件中创建记录的方式,但我也想包括图像:

v = Vehicle.create(
  vin: '1QJGY54INDG38946',
  color: 'grey',
  make_id: m.id,
  model_id: mo.id,
  wholesale_price: '40,000'
)

您可以使用 Ffaker gem to easily generate fake data and finally after creating the vehicle record you can update your record image attribute from the instance variable. Check Attaching File/IO Objects

这将是 db/seed.rb 文件的代码:

if Vehicle.count.zero?
  10.times do
    v = Vehicle.create(
      vin: FFaker::Code.ean,
      color: FFaker::Color.name,
      maker_id: m.id,
      model_id: m.id,
      wholesale_price: '40,000'
    )
    v.image.attach(io: File.open('/path/to/file'), filename: 'file.jpg')
  end
end

不要忘记将 ffaker gem 添加到您的 Gemfile 文件中。

正如上面的回答所述,它在 Edge Guides 中,对于难以获得正确路径的人来说,这是 seeds.rb 文件中的一行示例,将头像附加到第一个创建的用户:

User.first.avatar.attach(io: File.open(File.join(Rails.root,'app/assets/images/avatar.jpg')), filename: 'avatar.jpg')