gpt4 book ai didi

sql - rails : How to sum and display total quantity by category

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:58 25 4
gpt4 key购买 nike

我想按类别汇总总数量。

如何计算和显示它们?

显示图像如下;(项目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

view/orders/show.html.erb

<%= render @orders %>

view/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 %>

如果您能告诉我如何计算和显示总数,将不胜感激。

最佳答案

你可以这样做:

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

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

{ category1 => sum_quantity, ...  }

您只需迭代此哈希即可显示结果。

 <% 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 %>

关于sql - rails : How to sum and display total quantity by category,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37748480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com