Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seeding file uploads with CarrierWave, Rails 3

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?

like image 348
Nathan Kleyn Avatar asked Oct 11 '10 21:10

Nathan Kleyn


2 Answers

Turns out the documentation for CarrierWave is slightly wrong. There is a more up to date piece of code in the README at the GitHub repository for the project.

In a nutshell, though:

pi = ProductImage.create!(:product => product) pi.image.store!(File.open(File.join(Rails.root, 'test.jpg'))) product.product_images << pi product.save! 
like image 91
Nathan Kleyn Avatar answered Oct 01 '22 21:10

Nathan Kleyn


So long as your uploader is mounted to your model, using the mount_uploader method, you can seed your models with carrierwave using the relevant open method. This would be a more concise way of achieving the same thing. In my case I'm seeding from a URL:

Game.create([ {   :title => "Title",   :uuid_old => "1e5e5822-28a1-11e0-91fa-0800200c9a66",    :link_href => "link_href",    :icon => open("http://feed.namespace.com/icon/lcgol.png"),   :updated_at => "2011-01-25 16:38:46",    :platforms => Platform.where("name = 'iPhone'"),    :summary => "Blah, blah, blah...",    :feed_position => 0,    :languages => Language.where("code = 'de'"),    :tags => Tag.where(:name => ['LCGOL', 'TR', 'action']) }, {... 
like image 45
Nomas Prime Avatar answered Oct 01 '22 19:10

Nomas Prime