如何在Active Record查询界面中使用链接表

时间:2018-10-21 18:54:05

标签: ruby-on-rails ruby postgresql activerecord

我对Active Record还是比较陌生,并且有一个(希望很简单)的问题。

我有四个表Recipes(配方名称),Food(生菜,胡椒粉),Units(盎司,汤匙)和Ingredients(其他表格和数值)。

我想做的是这样的Recipes.Ingredients,然后得到“胡椒粉生菜,5汤匙胡椒粉,10盎司生菜”。

我如何使用以下模式来完成此任务。而且如果无法使用这种模式,我应该在它的位置构建什么。

模式如下:

  create_table "food", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "ingredients", force: :cascade do |t|
    t.bigint "recipes_id"
    t.bigint "units_id"
    t.bigint "food_id"
    t.decimal "quantity"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["food_id"], name: "index_ingredients_on_food_id"
    t.index ["recipes_id"], name: "index_ingredients_on_recipes_id"
    t.index ["units_id"], name: "index_ingredients_on_units_id"
  end

  create_table "recipes", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "name"
  end

  create_table "units", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

1 个答案:

答案 0 :(得分:1)

所以我从您的问题中了解到,您想要获得类似以下结果: Peppered Lettuce, 5 tbsp pepper, 10 oz Lettuce,其中胡椒生菜是Recipe的名称,而胡椒和生菜是Food,其中包含大量成分。

您不需要4个表即可获得此结果。您只需3. FoodRecipe以及一个多对多关联的中间表。

Recipe中可以包含多个Food项目,而1 Food个项目可以是多个Recipe对象的一部分。因此,FoodRecipe模型将具有many-to-many关联。对于这种关联,您需要另一个表。您可以将其命名为Foods_Recipes或简单地命名为Ingredients
这样,您的Ingredient模型将具有food_idrecipe_idnumeric_quantityunit_type

模式如下所示:

create_table "foods", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "ingredients", force: :cascade do |t|
    t.bigint "recipe_id"
    t.bigint "food_id"
    t.decimal "quantity"
    t.string "unit_type"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["food_id"], name: "index_ingredients_on_food_id"
    t.index ["recipe_id"], name: "index_ingredients_on_recipe_id"
  end

  create_table "recipes", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "name"
  end

您的模型如下所示: 食物模型:

class Recipe < ApplicationRecord
 has_many :ingredients
 has_many :foods,through: :ingredients
end

成分模型:

class Ingredient < ApplicationRecord
 belongs_to :recipe
 belongs_to :food
end

食物模型:

class Food < ApplicationRecord
 has_many :ingredients
 has_many :recipes,through: :ingredients
end