Jeremy Lynch
Jeremy Lynch

Reputation: 7210

Temporarily storing data in record to reduce query redundancy

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

Answers (2)

mgidea
mgidea

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

Mark
Mark

Reputation: 7625

Actually Rails should cache the query. It is not fired twice to the database.

Upvotes: 1

Related Questions