我有3个主表通过has_many through:
关联链接在一起。
主表是recipes
,ingredients
和allergens
。
食谱还通过ingredients
链接到recipe_ingredients
,并且ingredients
通过allergens
链接到ingredient_allergens
。
因此,总共有5个表。
我想做的就是看allergens
和recipe
有什么。
我阅读了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
来查看与该食谱相关的所有过敏原。
谢谢大家!
答案 0 :(得分:2)
includes
用于快速加载
尝试:
recipe.ingredients.preload(:allergens).map{|ing| ing.allergens.to_a }.flatten.uniq
这很简单:“将所有成分中的所有过敏原放入一个阵列中,然后去除重复的食物”,preload
是为了避免N + 1问题
答案 1 :(得分:0)
您可以添加索引:
# recipe.rb
has_many allergens, foreign_key: 'list_allergens_id', class_name: 'allergen'
# allergen.rb
belongs_to recipe, foreign_key: 'list_allergens_id', class_name: 'recipe'
之后,您可以检查每个食谱:
@recipe.list_allergens
您可以了解有关这种关联的更多信息:
https://guides.rubyonrails.org/association_basics.html#self-joins