Help optimizing get all children query (ActiveRecord/Ruby/Rails)
This is just a quick question on performance in an sql query using ruby and rails.
Basically I have a parent model and a bunch of children which have the variable of parent_ID. I first gather all the parents with a specific condition and then I cycle through each parent finding any children that match.
Unfortunately this is incredibly slow and I was wondering if开发者_JS百科 theres any help going in optimizing it.
@parents = Parent.where(:parent_id => 3) #This is passed in from params
@childrenArray =[]
@parents.each_with_index do |parent, index|
#TOOSLOW
@childrenArray[index] = Child.find(:all,:order=>"id",:conditions =>{:parent_ID=> parent.id})
end
One thing I thought is perhaps I should make an array of all the parent Ids to be searched and then do something like
child.find_by_parent_ID(myarrayofnumbershere)
However I don't know if this would be any better.
Any help or advice appreciated.
I'm very new to SQL and ruby. I'm aware a table joins would have been ideal here but I think I'm a bit late in my development to try it now. Also I need to serve up 2 seperate arrays. one of the parents and one of the children.
Try using the include
method, like so:
@parents = Parent.where(:parent_id => 3).include(:children)
Now rails will have fetched the associated children and you should be able to loop over @parents and access their children without additional queries, like so:
@parents.each do |p|
puts "#{p}'s children: #{p.children}"
end
精彩评论