ruby-on-rails - 模型关联使用includes方法关联3个表
问题描述
我有 3 个通过has_many through:
关联链接在一起的主表。
主表是recipes
、ingredients
和allergens
。recipes 也链接到ingredients
through recipe_ingredients
,并且ingredients
链接到allergens
through ingredient_allergens
。
所以总共有5张桌子。
我想做的就是看看allergens
arecipe
有什么。
我阅读了 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
查看与该食谱相关的所有过敏原。
多谢你们!
解决方案
includes
用于急切加载
尝试:
recipe.ingredients.preload(:allergens).map{|ing| ing.allergens.to_a }.flatten.uniq
这很简单“从所有成分中取出所有过敏原,放入一个数组并删除重复项”,并且preload
是为了避免 N+1 问题
推荐阅读
- python - 在使用 xarray 的 netCDF 文件上使用 Prophet
- typescript - 使用枚举作为泛型类型
- android - 如何使用正确的方法添加启动画面
- python - 使用 python selenium 抓取 HTML 表格
- macos - Mac OS 10.14.4 安装卡在 2014 年末的 Mac mini 中
- javascript - 过滤器从反应数组中删除一个元素
- c++ - 如何从 C++ 代码调用 SQL Server 中的 StoredProcedure?
- orm - ORM:续集:我可以在种子文件中使用原始查询吗?
- apache-kafka - 如何在spring cloud stream kafka中将重试与发送DLQ结合起来?
- sql - 如何为透视 ssas 表格模型的 Excel 中的日期列启用“日期过滤器”选项