我想在rake任务中创建用户和一堆图像。
10.times do
user = User.create :username => Faker::Name.name,
:email => Faker::Internet.email,
:password => "password",
:password_confirmation => "password"
10.times do
Image.create :user_id => user.id,
:name => Faker::Name.name,
:image => "../assets/musk_ox.jpg" # feeble attempt clearly doesn't work
end
end
我怎么能假装这个?图像不一定是独一无二的,但如果是这样的话,它们就会很棒。如果每个用户随机有5-10张图片也会很棒。
我正在使用carrierwave和mini_magick。
以下是真实用户仅供参考的表单。
<%= form_for @image, :html => {:multipart => true} do |f| %>
<% if @image.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@image.errors.count, "error") %> prohibited this image from being saved:</h2>
<ul>
<% @image.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.file_field :image %>
</div>
<%= f.hidden_field :user_id, value: current_user.id %>
<div class="actions">
<%= f.submit "Add Image", class: "btn btn-default" %>
</div>
<% end %>
答案 0 :(得分:0)
我最终这样做了:
10.times do
user = User.create :username => Faker::Name.name,
:email => Faker::Internet.email,
:password => "password",
:password_confirmation => "password"
rand(5...10).times do |i|
Image.create :user_id => user.id,
:name => Faker::Name.name,
# I get a rnd number between 5 & 10 above then just plug that index
# and path into the File class' join method
:image => File.open(File.join(Rails.root, "/lib/assets/#{i}.jpg"))