Seeding file uploads with CarrierWave, Rails 3
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 << piproduct.save!
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'])},{...
Here's an example script I incorporated into a seed.rb file for one of my projects.I'm sure it can be improved but it provides a good working example.
All the assets I'm pulling are stored within the app/assets/images and they have names matching the names of my Info objects (after I replace spaces with underscores and downcase the names).
Yes it does sound inefficient, but apart from putting those assets on an FTP somehwhere, it's the best solution I found for my remote server to be able to upload the files straight to S3 using Carrierwave and Fog.
My Info model has a has_one
association to a Gallery model, which has a has_many
association to a Photo model. The Carrierwave uploader is mounted on the 'file' (string) column of that model.
Info.all.each do |info| info_name = info.name.downcase.gsub(' ', '_') directory = File.join(Rails.root, "app/assets/images/infos/stock/#{info_name}") # making sure the directory for this service exists if File.directory?(directory) gallery = info.create_gallery Dir.foreach(directory) do |item| next if item == '.' or item == '..' # do work on real items image = Photo.create!(gallery_id: gallery.id) image.file.store!(File.open(File.join(directory, item))) gallery.photos << image end info.save! endend
This works flawlessly for me, but ideally I wouldn't have to package the files that I'm uploading to S3 within the assets folder. I'm more than open to suggestions & improvements.