Ruby on rails 如何在Rails中编写多个COUNT(*)子查询?

Ruby on rails 如何在Rails中编写多个COUNT(*)子查询?,ruby-on-rails,count,subquery,Ruby On Rails,Count,Subquery,如何像这样在Rails中编写子查询 select m.field1, m.field2, (select count(*) from details1 d1 where d1.id=m.field3) as count1, (select count(*) from details2 d2 where d2.id=m.field4) as count2, (select count(*) from details3 d3 where d3.id=m.fie

如何像这样在Rails中编写子查询

select
    m.field1,
    m.field2,
    (select count(*) from details1 d1 where d1.id=m.field3) as count1,
    (select count(*) from details2 d2 where d2.id=m.field4) as count2,
    (select count(*) from details3 d3 where d3.id=m.field5) as count3
from
    master m

数据库服务器是PostgreSQL。

NoMethodError:Master:Class Rails 3.2.3的未定义方法“set\u table\u name”。select本身似乎能够接受任意SQL字符串。谢谢你的提示。我自己的书签:应该包含从AR继承的内容。我将编辑我的答案。NoMethodError:Master:Class Rails 3.2.3的未定义方法“set\u table\u name”似乎select本身能够接受任意SQL字符串。谢谢你的提示。我自己的书签:应该包括AR的继承。我会编辑我的答案。
class Master < ActiveRecord::Base
  set_table_name "master"
end
masters = Master.select(%Q"master.field1, master.field2,
(select count(*) from details1 d1 where d1.id=m.field3) as count1,
(select count(*) from details2 d2 where d2.id=m.field4) as count2,
(select count(*) from details3 d3 where d3.id=m.field5) as count3").all