问题
I am currently trying to populate a development database on a project with a bunch of fake data, to simulate how it will look and operate with hundreds of articles / users. I looked into different gems to do the task - such as Factory Girl, but documentation was very lacking and I didn't get it - but ended up using the Populator and Faker gems and did the following rake task...
namespace :db do
desc "Testing populator"
task :populate => :environment do
require "populator"
require "faker"
User.populate 3 do |user|
name = Faker::Internet.user_name
user.name = name
user.cached_slug = name
user.email = Faker::Internet.email
user.created_at = 4.years.ago..Time.now
end
end
end
Works great...for text based data. However, all users have an avatar that can be uploaded via Paperclip attachment, as well as all regular content have thumbnail attachments in the same manner.
I understand the Populator gem simply does a straight population to the database and not necessarily running through ActiveRecord validations to do so..therefor I would assume Paperclip can't run to generate all the different thumbnails and needed (and uploaded to the proper directory) for the avatar if I just filled the field with a filepath in the rake task above.
Is there a way to populate fake images, via Populator or another way? Or perhaps a way to point the rake task at a directory of stock images on my hard drive to autogenerate random thumbnails for each record? Took a hunt on Google for a way, but have not turned up much information on the subject.
UPDATE
The final solution, based on pwnfactory's line of thinking...
namespace :db do
desc "Testing populator"
task :populate => :environment do
require "populator"
require "faker"
User.populate 3 do |user|
name = Faker::Internet.user_name
user.name = name
user.cached_slug = name
user.email = Faker::Internet.email
user.created_at = 4.years.ago..Time.now
end
User.all.each { |user| user.avatar = File.open(Dir.glob(File.join(Rails.root, 'sampleimages', '*')).sample); user.save! }
end
end
It basically loops back around and uploaded avatars from the sampleimages directory on all the records.
回答1:
To associate a random image in your task, you could try the following:
user.avatar = File.open(Dir.glob(File.join(Rails.root, 'sampleimages', '*')).sample)
where sampleimages is a directory containing avatars to be associated at random
回答2:
user.avatar = File.open(Dir['app/assets/images/*.jpg'].sample)
回答3:
One way I get around this is to put a conditional in my views.
Let's say your model is "user", and it has an avatar. Then you can do the following:
<% if product.avatar.exists? %>
... show the attached photo
<% else %>
.. show a default photo
<% end %>
This works for me with Paperclip, and I use it in my dev database all the time rather than worrying about having all the image attached to all the users.
来源:https://stackoverflow.com/questions/5792442/generating-paperclip-image-uploads-with-fake-data-ruby-on-rails-populator-fa