当我尝试在索引操作中显示链接的数据时 - 我无法避免使用标准包含的N + 1问题。例如:Rails - 关于“N + 1”的更多信息
Model 1 - Pet (let it will be animal: title:string. Pet can has many PetAttributeElems, they show attributes this Pet have and what values they have)
Model 2 - PetAttribute (this model contains only titles of attributes, like weight, age and 1000+ more attributes. PetAttribute has many PetAttributeElems - one attribute, such as weight, can be described for many Pets)
Model 3 - PetAttributeElem (this model belongs to pet and to petAttribute, also it has value field, that show value of attribute for pet.
当我做show
行动 - 我在HAML使用:
[email protected]_attribute_elems.includes(:pet_attribute).each do |elem|
="#{elem.pet_attribtute.title}: #{elem.value}"
但是,当我做index
行动我想用:
[email protected] do |pet|
-pet.pet_attribute_elems.includes(:pet_attribute).each do |elem|
="#{elem.pet_attribtute.title}: #{elem.value}"
这includes
方法将调用许多SQL查询,每pet
现在,我通过手动创建额外的对象是这样解决的:
@pet_elems = {}
PetAtributeElems.includes(:pet_attribute)
.where(pet_id:@pets.map(&:id)).each do |elem|
pet_id = elem.pet_id
if @pet_elems.include?(pet_id)
@pet_elems[pet_id] << elem
else
@pet_elems[pet_id] = [elem]
end
end
比我可以使用:
[email protected] do |pet|
-if @pet_elems.include?(pet.id)
[email protected]_elems[pet.id].each do |elem|
="#{elem.pet_attribtute.title}: #{elem.value}"
我怎么能解决这个任务更容易吗?
[也许你”重新解决错误的任务(半相关阅读)...](https://stackoverflow.com/questions/26247288/reducing-n1-queries-using-the-bullet-and-r spec-gems/26251892#26251892) –
我希望你是对的) 但现在我需要在没有N + 1查询的索引动作链接数据中显示 – user2572790