我有三个模型,分别如下:
现在我需要通过父级查找属于子级的资产。而“资产”有一个资产类型列。因此,我需要执行以下操作:
我该如何避免N+1查询?
Rails版本:5.1.6
Ruby版本:2.3.4
class Parent < ApplicationRecord
has_many :children
has_many :assets
end
class Child < ApplicationRecord
belongs_to :parent
end
class Asset < ApplicationRecord
belongs_to :parent
end
现在我需要通过父级查找属于子级的资产。而“资产”有一个资产类型列。因此,我需要执行以下操作:
Parent.first.children.each do |child|
child.parent.assets.find_by(asset_type: "first").asset_value
end
我该如何避免N+1查询?
Rails版本:5.1.6
Ruby版本:2.3.4
Child.each do |child|
的操作。 - luisenrike