Seeding DB with Paperclip Images with CSV
I needed to seed my app, hosted on Heroku, with new users. Since I wanted to created a lot of the them, I wanted to CSV. My users have avatars, so I wanted to upload those for the users as well.
Here’s how I did it:
1. I stored the original images I wanted to use for the avatars on AWS S3 (make sure that they are set with public permission to read them.
2. I created a CSV that had columns (in this order) for the users: username, email, password, password_confirmation, avatar. In the avatar field, I put the URL of the S3 image. I named this CSV file “user_data” and put it in the DB directory.
3. Using the answer to this Stack Overflow question, I created a file (I named user_seed.rake) in lib/tasks. The code in the file I used was:
namespace :csv do
desc “Import CSV Data”
task :import_stuff => :environment do
csv_file_path = ‘db/user_data.csv’
CSV.foreach(csv_file_path) do |row|
:username => row,
:email => row,
:password => row,
:password_confirmation => row,
:avatar => URI.parse(row)
puts “Row added!”
4. Run rake csv:import_stuff