首页 > 解决方案 > 模型关联使用includes方法关联3个表

问题描述

我有 3 个通过has_many through:关联链接在一起的主表。

主表是recipesingredientsallergens。recipes 也链接到ingredientsthrough recipe_ingredients,并且ingredients链接到allergensthrough ingredient_allergens
所以总共有5张桌子。

我想做的就是看看allergensarecipe有什么。

我阅读了 rails 文档,发现我可以使用该includes选项来做类似的事情,但在示例中,表是直接关联的。见下文。

class LineItem < ApplicationRecord
 belongs_to :book, -> { includes :author }
end

class Book < ApplicationRecord
 belongs_to :author
 has_many :line_items
end

class Author < ApplicationRecord
 has_many :books
end

目前我的模型看起来像这样:

# recipes:
  has_many :recipe_ingredients
  has_many :ingredients, through: :recipe_ingredients

# recipe_ingredients:
  belongs_to :recipe
  belongs_to :ingredient

# ingredients:
  has_many :recipe_ingredients
  has_many :recipes, through: :recipe_ingredients

# ingredient_allergens:
  belongs_to :ingredient
  belongs_to :allergen

# allergens:
  has_many :ingredient_allergens
  has_many :allergens, through: :ingredient_allergens

我现在一直在尝试以includes多种方式使用,但它们都不起作用。有谁知道includes在这种情况下是否可以使用?理想情况下,我希望能够打电话recipe.allergens查看与该食谱相关的所有过敏原。

多谢你们!

标签: ruby-on-railsruby-on-rails-5

解决方案


includes用于急切加载

尝试:

recipe.ingredients.preload(:allergens).map{|ing| ing.allergens.to_a }.flatten.uniq

这很简单“从所有成分中取出所有过敏原,放入一个数组并删除重复项”,并且preload是为了避免 N+1 问题


推荐阅读