2

我有:

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_score2 并且他们有另一个Score名称为“听力”和total_score3 的人。如何将所有这些概括为要求那些具有 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)

但它应该是这样做的一种轨道方式...... :) 希望

4

1 回答 1

0

尝试这个:

scope :by_scores, lambda do |params|
    if params.is_a? Hash
      query = joins(:scores)
      params.each_pair do |name, score|
        query = query.where( 'scores.total_score >= ? AND scores.name = ?', score, name)
      end
      query
    end
 end

然后像这样调用:

Evaluation.by_scores 'vision' => 2, 'hearing' => 3
于 2012-04-30T11:26:24.350 回答