Rails:如何按类别汇总和显示总数量

时间:2016-06-10 12:36:38

标签: sql ruby-on-rails ruby ruby-on-rails-4

我想按类别总计总数量。

如何计算和显示它们?

显示图像如下; (项目A和C是同一类别)

order A
  shop A

    name: item A
    category: 1
    quantity: 2

    name: item B
    category: 2
    quantity: 3

    name: item C
    category: 1
    quantity: 4

    <Total>     # I'd like to know how to calculate and display
    category 1: 6
    category 2: 3

如果你能给我任何建议,我们将不胜感激。

模型

class Order < ActiveRecord::Base
    has_many :shops
end

class Shop < ActiveRecord::Base
    belongs_to :order
    has_many :items
end

class Item < ActiveRecord::Base
    belongs_to :shop
    has_one :order, autosave: false, through: :shop
end

schema.rb

ActiveRecord::Schema.define(version: 20160610051929) do

  create_table "items", force: :cascade do |t|
    t.string   "name"
    t.integer  "category"
    t.integer  "quantity"
    t.integer  "shop_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "orders", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "shops", force: :cascade do |t|
    t.string   "name"
    t.integer  "order_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

orders_controller.rb

class OrdersController < ApplicationController
  def show
    @orders = Order.find(params[:id])
  end
end

查看/命令/ show.html.erb

<%= render @orders %>

查看/ orders / _order.html.erb

<%= order.name %><br>

<% order.shops.each do |shop| %>

    <%= shop.name %><br>

    <% shop.items.each do |item| %>

        name: <%= item.name %><br>
        category: <%= item.category %><br>
        quantity: <%= item.quantity %><br>
        <br>

    <% end %>

<% end %>

如果你能给我如何计算和显示总数,我们将不胜感激。

1 个答案:

答案 0 :(得分:3)

你可以这样做:

Item.group(:category).sum(:quantity)

您将获得这样的哈希构建:

{ category1 => sum_quantity, ...  }

你只需要迭代这个Hash来显示结果。

 <% shop.items.each do |item| %>
    name: <%= item.name %><br>
    category: <%= item.category %><br>
    quantity: <%= item.quantity %><br>
    <br>

<% end %>
<% shop.items.group(:category).sum(:quantity).each do |category, sum| %>
       Category <%=category%> : <%= sum %><br>
<% end %>