Tuesday, August 4, 2009

Avoid multi-level associations using named scope

I had the a "local_address" method in Enrollment which looks for first local address

class Enrollment < ActiveRecord::Base

has_many :addresses

def local_address
addresses.local.last
end

end

class Address < ActiveRecord::Base

belongs_to :enrollment
belongs_to :address_type

named_scope :local, {
:joins => "LEFT OUTER JOIN address_types ON address_types.id = addresses.address_type_id",
:conditions => "address_types.name = 'Local'"
}

end


Calling the "@enrollment.local_address" then leads to very unoptimized queries. To optimized it I had to call "Address.find" directly from the "local_address" method.

def local_address
- addresses.local.last
+ Address.last :include => :address_type, :conditions => ["address_types.name = 'Local' and enrollment_id = ?", id]
end

No comments:

Blog Archive