ruby-on-rails - 如何在我的种子文件中存储连接表实例的多个 ID?
问题描述
下面的代码是我的种子文件。我已经在迁移和模型中建立了很多直通关系。我想知道如何创建具有多种成分的配方成分实例。我在下面的内容为recipingredient 返回null。
Ingredient.delete_all
Recipe.delete_all
RecipeIngredient.delete_all
butter = Ingredient.create(name: 'Butter', image: 'butter.png')
cinnammon = Ingredient.create(name: 'Cinnammon', image: 'cinnammon.png')
Ingredient.create(name: 'Cocoa Powder', image: 'cocoa.png')
Ingredient.create(name: 'Cream Cheese', image: 'cream-cheese.png')
Ingredient.create(name: 'Eggs', image: 'eggs.png')
Ingredient.create(name: 'Flour', image: 'flour.png')
Ingredient.create(name: 'Heavy Cream', image: 'cream.png')
Ingredient.create(name: 'Milk', image: 'milk.png')
Ingredient.create(name: 'Nuts', image: 'nuts.png')
Ingredient.create(name: 'Oil', image: 'oil.png')
Ingredient.create(name: 'Salt', image: 'salt.png')
Ingredient.create(name: 'Sugar', image: 'sugar.png')
Ingredient.create(name: 'Vanilla', image: 'vanilla.png')
ccp = Recipe.create(name: 'Chocolate Chip Cookies', difficulty: 1)
cheesecake = Recipe.create(name: 'Cheesecake', difficulty: 2)
RecipeIngredient.create(ingredient_id: [cinnammon.id,butter.id],recipe_id: ccp.id)
迁移是:
class CreateRecipes < ActiveRecord::Migration[6.0]
def change
create_table :recipes do |t|
t.string :name
t.integer :difficulty
t.timestamps
end
end
end
class CreateIngredients < ActiveRecord::Migration[6.0]
def change
create_table :ingredients do |t|
t.string :name
t.string :image
t.timestamps
end
end
end
class CreateRecipeIngredients < ActiveRecord::Migration[6.0]
def change
create_table :recipe_ingredients do |t|
t.integer :recipe_id
t.integer :ingredient_id
t.timestamps
end
end
end
我也尝试使用recipe_id 或component_id 的实际整数创建recipingredient 实例,但它也不起作用。我可以使用序列化吗?不确定序列化是如何工作的。任何帮助将不胜感激,谢谢!
解决方案
确保关系配置良好
class Recipe < ApplicationRecord
has_many :ingredients, through: :recipe_ingredients
end
class Ingredient < ApplicationRecord
has_many :recipes, through: :recipe_ingredients
end
class RecipeIngredient < ApplicationRecord
belongs_to :recipe
belongs_to :ingredient
end
然后,在你的种子文件中你应该有这样的东西:
butter = Ingredient.create(name: 'Butter', image: 'butter.png')
cinnammon = Ingredient.create(name: 'Cinnammon', image: 'cinnammon.png')
a_recipe = Recipe.new(name: 'Recipe name', difficulty: 1)
a_recipe.ingredients << [butter, cinnamon]
a_recipe.save
这不是最优雅的解决方案,但可以解决问题
推荐阅读
- postgresql-9.5 - 无法按 jsonb 类型的字段中的节点进行过滤
- reactjs - 反应查询,无效的钩子调用
- python - 如何使用 python 关闭 Internet 选项卡
- docker - TLS:验证客户端证书失败:x509:证书指定了不兼容的密钥用法
- java - 将默认 Java 路径更改为 FreeBSD 中的其他路径
- r - Bind_rows() error: "Argument 1 must have names" // 在 tidyverse 更新后发生
- python - pip 自动下载要求
- for-loop - time.sleep() 最后没有按预期工作
- flutter - Flutter Dart 版本未升级到 2.9.0
- xamarin.forms - Xamarin.Forms 为不同平台(android、ios)设置不同的列定义