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 =>
[:positionawarenesses])
I’m trying to avoid having to do (which makes another query):
@awarenesses[0].positionawarenesses.find_by_position_id(12).level
How do I get to that information using the result of the first bit
there?
Not sure if that’s what you’re trying to achieve but
@awarenesses[0].positionawarenesses.select { |pa| pa.position_id == 12
}.first.level
might do the job.
Paolo
Paolo N. wrote:
@awarenesses[0].positionawarenesses.select { |pa| pa.position_id == 12
}.first.level
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,
awareness_id)
find(
:all,
:conditions => [
“position_id = ? and awareness_id = ?”,
position_id,
awareness_id
]
)
end
end
And in your controller:
PositionAwareness.find_by_position_id_and_awareness_id(12,
@awarenesses[0].id)
Chris
On Aug 8, 9:46 am, Brett B. [email protected]