ActiveRecord Group and Count - count_id来自哪里?

时间:2015-02-23 21:13:27

标签: activerecord

我有Order加入的ItemOrderItem个模型:

class OrderItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :item

此查询查找最受欢迎项目的ID:

OrderItem.group(:item_id).order("count_id DESC").count("id").first(10).map(&:first)

这样可行,但count_id是什么?为什么这样做?幕后花絮order("count_id...幕后发生了什么?

1 个答案:

答案 0 :(得分:0)

<button style="position:absolute;top:116.5px; left:113px;" type="button" class="btn btn-default btn-lg" data-container="body" data-toggle="popover" data-placement="right" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus."> <span style="font-size:5.0em;" class="glyphicon glyphicon-home" aria-hidden="true"></span> </button>是Rails为SQL聚合函数count_id提供的别名。

COUNT("order_items"."id")计算每个项目的行数:

OrderItem.group(:item_id).count(:id)

SELECT COUNT("order_items"."id") AS count_id, item_id AS item_id FROM "order_items" GROUP BY item_id 部分背后的魔力在于ActiveRecord::Calculations。别名在此处确定:

count_id

aggregate_alias = column_alias_for([operation, column_name].join(' ')) 列表的方法评论显示了这个例子:

column_alias_for

之后,# column_alias_for("count", "id") # => "count_id" 列出从最大到最小的项目出现次数。返回值将是哈希,其中键是项ID,值是出现次数。

order抓取发生次数最多的10个项目,first提取map个值。