當我嘗試在索引操作中顯示鏈接的數據時 - 我無法避免使用標準包含的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