首页 > 解决方案 > 如何在我的种子文件中存储连接表实例的多个 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 实例,但它也不起作用。我可以使用序列化吗?不确定序列化是如何工作的。任何帮助将不胜感激,谢谢!

标签: ruby-on-railsjoindatabase-migrationhas-many-throughseeding

解决方案


确保关系配置良好

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

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


推荐阅读