首先也是最重要的:命名作用域已死
我建议您执行以下操作:
class Players < ActiveRecord::Base
....
def self.with_win_count
#inner join if you want to filter out those who doesn't have any match, otherwise is should be left outer
joins("inner join (select Player_ID, count(Match_ID) as win_count from Results where Win = true group by Player_ID) t on (t.Player_ID = Player.ID)")
end
end
#somewhere in controller you would do
best_players = Player.with_win_count.where("win_count > ?", [10]).order("win_count DESC")
如果您希望它出现在结果表中:
class Results < ActiveRecord::Base
....
def self.with_win_count
joins("inner join (select Player_ID, count(Match_ID) as win_count from Results where Win = true group by Player_ID) t on (t.Player_ID = Results.Player_ID)")
end
end
这会起作用,但我觉得它有点难看。
如果您想要嵌套查询中的条件计数,简单的方法是:
class Players < ActiveRecord::Base
....
def self.with_match_count(conditions)
#inner join if you want to filter out those who doesn't have any match, otherwise is should be left outer
joins("inner join (select Player_ID, count(Match_ID) as match_count from Results where #{conditions} group by Player_ID) t on (t.Player_ID = Player.ID)")
end
end
some_players = Player.with_match_count("Win = true").where("match_count > ?", [10]).order("match_count DESC")
!!!conditions
请注意,如果参数将直接由用户输入构建,则很容易发生 SQL 注入。