2017-03-01 50 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

相关问题