如何在我的种子文件中为一个连接表的实例存储多个id?

问题描述 投票:0回答:1

下面的代码是我的种子文件。我已经在迁移和模型中设置了has many through的关系。我想知道如何创建一个有多个成分的recipeingredient的实例。我下面的recipeingredient返回的是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或 ingredient_id的整数来创建recipeingredient的实例,但也不行。也许我可以使用序列化?不过不知道序列化是如何工作的。任何帮助都将被感激,谢谢你!

ruby-on-rails join database-migration has-many-through seeding
1个回答
1
投票

一定要把关系配置好

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

这不是最优雅的解决方案,但可以做到这一点。


0
投票

RecipeIngredient 只接受单个 ingredient_id因此,对于黄油和肉桂,你必须建立一个 RecipeIngredient 每个。

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

之后,一定要在你的 "has many "关系中设置 recipe.rb

has_many :ingredients

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

© www.soinside.com 2019 - 2024. All rights reserved.