使用ActiveRecord批处理查询

时间:2014-07-30 18:17:41

标签: ruby-on-rails activerecord

有没有办法批量独立(即不依赖于以前的值)查询到数据库的单个请求,以防止往返?

我打算用它来从几个不相关的数据模型中读取数据,因此连接和视图是不够的。

这是我正在尝试的一个非常粗略的想法:     

queries = {
  # What       Relation or SQL
  top_duck:    Duck.limit(1),          # We can't use first directly
  cow_count:   Cow.select('count(*)'), # We can't use count directly
  petals_lost: Flower.group_by('petals_lost').order_by('petals_lost')
                     .select('average(petals_lost) as average_petals_lost'),
  avg_score:   "select avg(score), stddev(score) from games"
}

bq = BatchQuery.new(queries)
# And in one trip...
bq.execute # => Hash<DB::Result> suffices for now; next step: typecasting

0 个答案:

没有答案