我可以运行此查询以生成区域哈希并按答案分组(包括零计数):
Region.includes(:answers).group("regions.region").count("answers")
产生:
{"blar"=>0, "East"=>0, "East Midlands"=>11, "London"=>8, "North East"=>0, "North West"=>0, "Northern Ireland"=>0, "Rest of World"=>89, "Scotland"=>0, "South East"=>0, "South West"=>0, "Wales"=>0, "West Midlands"=>0, "Yorkshire and the Humber"=>0}
但是,当我希望针对特定问题获得此结果(包括计数零)时,它仅显示带有答案的区域的散列。
询问:
Region.includes(:answers).where("answers.question_id = 14").group("regions.region").count("answers")
产生:
{"East Midlands"=>3, "London"=>1, "Rest of World"=>4}
我知道查询将只选择 question_id 的答案,所以这给出了给定的输出,但我尝试了许多不同的查询(包括 LEFT OUT JOINS)并且无法获得所需的结果。
以供参考:
地区 has_many :answers
回答belongs_to :region
回答belongs_to:问题
谢谢