Seeding file uploads with CarrierWave, Rails 3

Viewed 16272

I'm trying to seed a database in Rails 3 with images using CarrierWave, however nothing I try seems to work short of having to upload them all by hand.

pi = ProductImage.new(:product => product)
pi.image = File.open(File.join(Rails.root, 'test.jpg'))
pi.store_image! # tried with and without this
product.product_images << pi
product.save!

Anybody know how to seed using CarrierWave at all?

6 Answers

Building on @joseph jaber's comment this worked a treat for me:

The code below shoud be in seeds.rb

20.times do
        User.create!(
            name: "John Smith",
            email: "john@gmail.com",
            remote_avatar_url: (Faker::Avatar.image)
        )
    end

This will create 20 users and give each one a different avatar image.

I have used the faker gem to generate the data but all Faker::Avatar.image does is return a standard url, so you could use any url of your choice.

The above example assumes that the User models attribute where you store you images is called avatar

If the attribute was called image you would write like this:

remote_image_url: (Faker::Avatar.image)

Related