Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
)
like image 798
Anderson Avatar asked Nov 19 '18 20:11

Anderson


People also ask

What is Seeds RB file?

The seeds.rb file is where the seed data is stored, but you need to run the appropriate rake task to actually use the seed data. Using rake -T in your project directory shows information about following tasks: rake db:seed. Load the seed data from db/seeds.rb. rake db:setup.

What is seed RB in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.


2 Answers

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('/path/to/file'), filename: 'file.jpg')
  end
end

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

like image 184
hernanvicente Avatar answered Sep 21 '22 02:09

hernanvicente


As the above answer states it's in the Edge Guides, for people having trouble getting the path right, this is an example of a line in the seeds.rb file attaching an avatar to the 1st created user:

User.first.avatar.attach(io: File.open(File.join(Rails.root,'app/assets/images/avatar.jpg')), filename: 'avatar.jpg')
like image 31
Dé Leijs Avatar answered Sep 22 '22 02:09

Dé Leijs