【发布时间】:2019-04-24 23:19:28
【问题描述】:
我有两个模型。一是品类,二是产品。我已经填充了类别表,现在我需要使用类别 ID 填充产品。 我正在为这个人群使用faker。
模型和seeds.rb文件是这样的
class Product < ApplicationRecord
belongs_to :categories
end
class Category < ApplicationRecord
has_many :products
end
种子.rb
category = Category.ids
100.times do
Product.create!([{
name_product: Faker::Commerce.product_name
},
{
value_product: Faker::Commerce.price
},
{
category_id: category.sample
}
])
end
但我不断收到错误“验证失败。类别是必要的”,即使传递了类别 ID。 如果我评论产品模型中的关联,它可以工作,但这不是解决方案。
【问题讨论】:
-
您能否确认您的
category变量(最好重命名为category_ids或类似名称)肯定包含一组ID?
标签: ruby-on-rails ruby