Как использовать таблицу ссылок с интерфейсом запросов Active Record - PullRequest
0 голосов
/ 21 октября 2018

Я все еще относительно новичок в 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 голосов
/ 21 октября 2018

так что я понимаю из вашего вопроса, что вы хотите получить результаты, такие как: Peppered Lettuce, 5 tbsp pepper, 10 oz Lettuce, в котором Peppered Lettuce имеет Recipe имя, а Pepper и Lettuce являются 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...