使用rake和faker gem创建具有设计用户ID的帖子

时间:2016-12-29 12:01:06

标签: ruby-on-rails devise activemodel rake-task faker

我是一个noobie。我试图用faker gem生成假数据使用rake populate任务我收到错误验证失败用户必须存在。这是我的任务文件:

 namespace :db do
  desc "Fill database with test data"
  task populate: :environment do
   10.times do |u|
     name = Faker::LordOfTheRings.character
     email = Faker::Internet.email
     password = "password"
     User.create!( name: name,
                email: email,
                password: password,
                password_confirmation: password)
      end

   User.all.each do |user|
     10.times do |n|
       title = Faker::Lorem.sentence
       body = Faker::Lorem.paragraphs(1)
       created_at = 2.years.ago..Time.now
       user_id = user.id
       Post.create!(
                  title: title,
                  body: body,
                  created_at: created_at,
                  user_id: user_id
                                )

        end
     end
   end
 end

我还需要在帖子表中提供用户引用。提前致谢

0 个答案:

没有答案