2017-03-01 56 views
0

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

我怎麼能解決這個任務更容易嗎?

+0

[也許你」重新解決錯誤的任務(半相關閱讀)...](https://stackoverflow.com/questions/26247288/reducing-n1-queries-using-the-bullet-and-r spec-gems/26251892#26251892) –

+0

我希望你是對的) 但現在我需要在沒有N + 1查詢的索引動作鏈接數據中顯示 – user2572790

回答

1

你正在走下一個非軌道約定路徑。

移動代碼出來的意見,它只是

​​3210

進行部分處理顯示

# _pet_attribute_elems.html.haml 
="#{pet_attribute_elem.pet_attribtute.title}: #{pet_attribute_elem.value}" 

在控制器,執行查詢

def show 

    @pet = Pet.find(...) 
    @pet_attribute_elems = @pet.pet_attribute_elems.includes(:pet_attribute) 

end 

def index 

    @pet_attribute_elems = PetAttributeElem.includes(:pet_attribute) 

end 
+0

也許你是對的,但這並不能解決很多查詢的問題 – user2572790

+0

它將只是一個或兩個查詢。這並不是很多 – Swards

相關問題