Eager loading w/ :through question

I’m doing an absolutely insane amount of queries, so I starting looking
into how to fix it, because there isn’t really a reason to, as I can get
the relevant data with just one.

Essentially it looks like this. I have a list of training criteria
called “awarenesses”, that have a certain amount of relevancy to a given
“position”, the “positionawarenesses” is the join object that defines
this relationship and has a field that says how important it is called
“level” (along with an “awareness_id” and “position_id” of course.

This query gives me a table with everything I should need… including
the “level”

@awarenesses = Awareness.find(:all, :include =>


I’m trying to avoid having to do (which makes another query):


How do I get to that information using the result of the first bit

Not sure if that’s what you’re trying to achieve but

@awarenesses[0].positionawarenesses.select { |pa| pa.position_id == 12

might do the job.


Paolo N. wrote:

@awarenesses[0].positionawarenesses.select { |pa| pa.position_id == 12

This definitely gets the value I’m looking for, which cut my queries in
half, yay! Not sure about the efficiency as I’m using that some 2000
times in a loop? Alas the values are different every time.

Given that positionawarenesses has its own properties, you could also
pull this out into its own model. If nothing else, this would create a
very efficient query.

class PositionAwareness < ActiveRecord::Base
:belongs_to :awareness
:belongs_to :position

def self.find_by_position_id_and_awareness_id(position_id,

:conditions => [
“position_id = ? and awareness_id = ?”,

And in your controller:


On Aug 8, 9:46 am, Brett B. [email protected]