Group and count in Rails

后端 未结 7 1949
傲寒
傲寒 2021-02-01 12:06

I know I\'ve seen this before but I can\'t find anything now. I want to group a query by a certain column and be able to display how many are in each group. I got the first part

7条回答
  •  太阳男子
    2021-02-01 12:48

    Just add a :select option:

    @line_items = @project.line_items.all(
      :group  => "device_id",
      :select => "device_id, COUNT(*) as count"
    )
    

    Then each @line_item will have a count attribute.

提交回复
热议问题