Search code examples
rubyrails-activestorage

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


I have a class called vehicles which can have an image attached to it. I have made a default image to display if no other image was uploaded in the vehicles.rb file.

I would like to include images in the seed.rb file so I don't have to manually upload all images. Is this possible?

Help is much appreciated thanks.

Here is my 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

Here is how i am creating records in my seed file but I would like to include the images as well:

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

Solution

  • You could use the 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

    This would be the code of db/seed.rb file:

    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(File.join(Rails.root,'app/assets/images/photo.jpg')),
          filename: 'photo.jpg'
        )
      end
    end
    

    Don't forget to add the ffaker gem to your Gemfile file.