简体   繁体   English

如何为种子分配User_ID

[英]How do I assign a User_ID to the seed

I'm trying to assign random user_id's to products that are generated from the seeds database. 我正在尝试将随机的user_id分配给从种子数据库生成的产品。 Everything is generating for me as I want it except for the user_id which is rendering nil. 除了user_id呈现nil之外,一切都为我生成了。 I'm trying to get a better understanding of how the belongs_to interaction works - any help here would be awesome! 我正在尝试更好地了解belongs_to交互的工作原理,这方面的任何帮助都很棒!

10.times do |n|
 name = Faker::Name.name
 job = Faker::Company.name
 User.create!(name: name,
               job: job  )
end

10.times do |n|
 users = User.all
 name = "Turkey"
 price = Random.rand(42-10) + 10
 user_id = users[1..10] 
 Product.create!(name: name,
                 price: price,  
                 user_id: user_id)
end             

Thanks in advance for the help! 先谢谢您的帮助!

Edit ** Thanks for the help everyone. 编辑**谢谢大家的帮助。 This is what I ended up changing the code to. 这就是我最终将代码更改为的内容。

users = User.order(:created_at).take(6)
10.times do |n|
name = "Turkey"
price = Random.rand(42-10) + 10
users.each { |user| user.products.create!(name: name, price: price)}
end               

You probably mean this: 您可能是这个意思:

user_id = users.last.id

Or possibly: 或可能:

user_id = users.shuffle.last.id

I'm not sure what your range notation 1..10 is intending. 我不确定您的范围标记1..10打算做什么。 Arrays are 0-indexed. 数组是0索引的。

User id will automatically get generated for each new user in sequential order. 用户ID将自动按顺序为每个新用户生成。 There is no need to have the "user_id" field there. 不需要在那里有“ user_id”字段。

Like Mukul215 said the ID will be generated automatically in sequential order. 就像Mukul215所说的那样,ID将按顺序自动生成。 It is BAD practice to hard code ID's in the seed. 在种子中对ID进行硬编码是不明智的做法。

I'm not 100% what you're asking in terms of assigning a random user id to the product. 关于为产品分配随机用户ID的要求,我不是100%。 From your comment on @tadman answer it seems you just want a product to belong to each one of the users. 从您对@tadman答案的评论看来,您似乎只希望一种产品属于每个用户。 Why not just do something like this: 为什么不做这样的事情:

10.times do |n|
 name = Faker::Name.name
 job = Faker::Company.name
 User.create!(name: name, job: job)
end

User.all.each do |user|
 name = "Turkey"
 price = Random.rand(42-10) + 10
 user.products.create!(name: name, price: price)
end     

Assuming your User model has many products and a product belongs to a User that should get your desired outcome. 假设您的用户模型有很多产品,并且某个产品属于某个用户,那么您应该会获得所需的结果。

user.products will automatically assign the user.id to the user_id field to the product record when sending build or create 发送buildcreate时, user.products会自动将user.id分配给product记录的user_id字段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM