I have:
class Evaluation < ActiveRecord::Base
has_many :scores
end
class Score < ActiveRecord::Base
scope :for_disability_and_score,
lambda { |disability, score|
where('total_score >= ? AND name = ?', score, disability)
}
end
The scores
table has a total_score
field and a name
field.
How can i write a scope
to ask for only those evaluations
which have a Score
with name 'vision' and total_score
of 2 and they have another Score
with name 'hearing' and total_score
of 3.
And how can all this be generalized to ask for those evaluations which have n scores with my parameters?
In raw sql it would be like:
I managed to do it in raw sql:
sql = %q-SELECT "evaluations".*
FROM "evaluations"
INNER JOIN "scores" AS s1 ON "s1"."evaluation_id" = "evaluations"."id"
INNER JOIN "target_disabilities" AS t1 ON "t1"."id" = "s1"."target_disability_id"
INNER JOIN "scores" AS s2 ON "s2"."evaluation_id" = "evaluations"."id"
INNER JOIN "target_disabilities" AS t2 ON "t2"."id" = "s2"."target_disability_id"
WHERE "t1"."name" = 'vision' AND (s1.total_score >= 1)
AND "t2"."name" = 'hearing' AND (s2.total_score >= 2)-
Here the point is to repeat this:
INNER JOIN "scores" AS s1 ON "s1"."evaluation_id" = "evaluations"."id"
and this (by replacing s1 to s2 and s3 and so forth):
WHERE (s1.total_score >= 1)
But it should be a rails way of doing this... :) Hopefully