我对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
答案 0 :(得分:1)
所以我从您的问题中了解到,您想要获得类似以下结果:
Peppered Lettuce, 5 tbsp pepper, 10 oz Lettuce
,其中胡椒生菜是Recipe
的名称,而胡椒和生菜是Food
,其中包含大量成分。
您不需要4个表即可获得此结果。您只需3. Food
,Recipe
以及一个多对多关联的中间表。
Recipe
中可以包含多个Food
项目,而1 Food
个项目可以是多个Recipe
对象的一部分。因此,Food
和Recipe
模型将具有many-to-many
关联。对于这种关联,您需要另一个表。您可以将其命名为Foods_Recipes
或简单地命名为Ingredients
。
这样,您的Ingredient
模型将具有food_id
,recipe_id
,numeric_quantity
和unit_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