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"])
预先感谢您的任何答案。
.select("count(...) as col1, count(...) as col2")
如果您记住以下两点,则您的版本应该可以正常工作:
M.where(...).select(...)
即使查询仅返回一行,也将返回多个内容。inspect
输出中并不意味着它不存在。您在没有GROUP BY的情况下进行汇总,因此只能返回一行。要展开该行,您可以说first
:
counts = Survey.where(...)
.select('count(case when role_composer then true end) as composers, count(case when role_performer then true end) as performers')
.first
那会给你一个Survey
实例counts
。如果您counts
在控制台中查看该内容,则会看到类似以下内容的内容:
#<Survey >
该inspect
输出只包括列中的值(即事物的Survey
类知道),但composers
和performers
将在那里。但是,由于ActiveRecord不知道它们应该是什么类型,因此它们将作为字符串输出:
composers = counts.composers.to_i
performers = counts.performers.to_i
select
如果您要寻找的话,您的一切都会在那里。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句