我有:
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
该scores
表有一个total_score
字段和一个name
字段。
我怎么能写一个scope
只要求那些evaluations
名称Score
为“视觉”和total_score
2 并且他们有另一个Score
名称为“听力”和total_score
3 的人。如何将所有这些概括为要求那些具有 n 分数的评估用我的参数?
在原始 sql 中,它会是这样的:
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)-
这里的重点是重复这一点:
INNER JOIN "scores" AS s1 ON "s1"."evaluation_id" = "evaluations"."id"
这(通过将 s1 替换为 s2 和 s3 等等):
WHERE (s1.total_score >= 1)
但它应该是这样做的一种轨道方式...... :) 希望