Reputation: 7210
The example below shows redundancy as the database is queried twice for exactly the same thing.
.div1
- towns.each do |town|
= town.name
- town.residents.where(:age => 14).each do |r|
%p= r.name
.div2
- towns.each do |town|
= town.name
- town.residents.where(:age => 14).each do |r|
%p= r.name
Is there anyway I can simplify this?
Upvotes: 0
Views: 44
Reputation: 494
you can optimize the queries by including or preloading the relations object.
towns = towns.preload(:residents)
this will select the residents records of the towns ahead of time
if you are only looking for the towns with residents that are age 14 then
towns = towns.joins(:residents).preload(:residents).where(:residents => {:age => 14}).uniq
Upvotes: 0
Reputation: 7625
Actually Rails should cache the query. It is not fired twice to the database.
Upvotes: 1