如何在种子文件中存储连接表实例的多个 ID?



下面的代码是我的种子文件。我已经在迁移和模型中设置了许多通过关系。我想知道如何创建具有多种成分的食谱成分实例。我在下面的内容返回食谱成分的空。

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 或 ingredient_id 创建配方成分实例,但它也没有用。我可以使用序列化吗?不确定序列化是如何工作的。任何帮助将不胜感激,谢谢!

确保关系配置良好

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

这不是最优雅的解决方案,但可以解决问题

RecipeIngredient只接受一个ingredient_id,所以对于黄油和肉桂,你必须分别创建一个RecipeIngredient

RecipeIngredient.create(ingredient_id: cinnamon.id, recipe_id: ccp.id)
RecipeIngredient.create(ingredient_id: butter.id, recipe_id: ccp.id)

在此之后,请确保在您的recipe.rb中设置了许多关系

has_many :ingredients

然后,您可以调用ccp.ingredients来显示肉桂和黄油。

最新更新