Rails 4.1、Postgres 9.3,部署到 Heroku
我正在尝试减少对数据库的调用次数。
我有一个大表,调查,有多个布尔列,例如role_composer
, role_performer
,等等。
控制器有多个查询,例如
@sample = Survey.where(...whatever...)
@Composers = @sample.count("case when role_composer then true end")
...
@Performers = @sample.count("case when role_performer then true end")
这工作正常,但会导致对数据库的许多单独查询,这些查询仅因选择中的表达式而有所不同。有没有一种方法可以将其构造为具有多个聚合/计算列的一个查询?我还使用average() 和表达式进行查询,但最常见的是count()。
在 postgres 中,这是有效的:
SELECT count(case when role_composer then true end) as "COMPOSERS", count(case when role_performer then true end) as "PERFORMERS" from surveys;
有什么方法可以使用 @sample 上的 Activerecord 方法而不是诉诸 find_by_sql() 来做到这一点?
我尝试了多种方法均未成功:.count().count()
, .count([array])
, .select("count(...) as col1, count(...) as col2")
, .select(["count(...) as col1", "count(...) as col2"])
预先感谢您的任何答复。