在Rails 4中将更多项添加到seeds.rb中

时间:2015-04-09 06:20:18

标签: ruby-on-rails ruby database ruby-on-rails-4 model-view-controller

我的应用程序有类别和子类别, 要添加类别,请在db/seeds.rb此代码中输入 category = Category.create!(name: "Video and animation") #it works

子类别我输入subcategory = Subcategory.create!(name: "Intro", "Animation & 3D", "Editing and Post Production", "Other" ) #it doesn't work

然后在最后category.subcategories << subcategory

中将子类别指定给类别i

当我在上面的代码中创建一个名字更多的子类别时出现问题,我做错了什么?谢谢。

2 个答案:

答案 0 :(得分:2)

假设您有一个关系subcategory belongs_to category,子类别表包含category_id字段:

category = Category.create!(name:  "Video and animation") 
["Intro", "Animation & 3D", "Editing and Post Production", "Other"].each do |name|
  subcategory = Subcategory.create!(name: name, category: category)
end

答案 1 :(得分:1)

以下是解决方案:

@category = Category.create!(name: "Video and animation")

["Intro", "Animation & 3D", "Editing and Post Production", "Other"].each do |name|

@subcategory = Subcategory.create!(name: name, category_id: @category.id)

end