为两个依赖项目和用户的注释播种数据库

时间:2016-11-29 21:03:53

标签: ruby-on-rails

我正在尝试播放我的评论数据库,但由于我不太确定如何操作而无法正常工作

#Comments Creation
users = User.order(:created_at).take (6)
projects = Project.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(5)
projects.each { |project| project.comments.create!(body: content , user_id: @user.id) }
end

我得到的错误

rails db:seed
rails aborted!
NoMethodError: undefined method `id' for nil:NilClass

Comments.model

belongs_to :user
belongs_to :project

路由

resources :projects do
resources :comments
end

还有db for comments

  

ID /体/ USER_ID / PROJECT_ID

有什么想法吗?谢谢:))

----解决方案! ----

感谢Gaston

users = User.order(:created_at).take (6)
projects = Project.order(:created_at).take(6)
50.times do
    users.each do |user|
        content = Faker::Lorem.sentence(5)
        projects.each { |project| project.comments.create!(body: content, user_id: user.id) }
    end 
end

1 个答案:

答案 0 :(得分:0)

我认为这会起作用

users = User.order(:created_at).take (6)
projects = Project.order(:created_at).take(6)
50.times do
    users.each do |@user|
        content = Faker::Lorem.sentence(5)
        projects.each { |project| project.comments.create!(body: content , user_id: @user.id) }
    end 
end

这是另一种选择

例如,如果您希望每个项目总共只有60个

users = User.order(:created_at).take (6)
projects = Project.order(:created_at).take(6)

projects.each do |project| 
    10.times do 
        users.each do |@user|
            content = Faker::Lorem.sentence(5)
            project.comments.create!(body: content , user_id: @user.id) }
        end 
    end 
end 

最后,播种用户

  6.times do |n|
    name = Faker::Name.name
    email = "sasexample-#{n+1}@example.org"
    User.create!( 
                name: name, 
                email: email,
                password:   "exampleexample")
   end