简体   繁体   English

Rails 5分组,求和并在视图中显示

[英]Rails 5 group by, sum and show in view

I have two models in Rails 5 and usign Postgres: 我在Rails 5和USign Postgres中有两个模型:

class Sale < ApplicationRecord
attribute :total (among others)
   belongs_to :categorys
end  

class Category < ApplicationRecord
  attritubte :name (among others)
  has_many :sales
end

so how can i get sales group by category and sum the total of sales in each category? 那么我如何才能按类别获得销售分组并汇总每个类别的销售总额? and how can i show it in my view (in a instance variable). 以及如何在我的视图中显示它(在一个实例变量中)。 For example i want to show in my view this: 例如,我想在我的视图中显示以下内容:

CategoryOne : Total $3000 (maybe the result is a hash but how can i show it in the view? CategoryOne:总计$ 3000(也许结果是哈希值,但如何在视图中显示呢?

CategoryTwo : Total $4000 二类:总计$ 4000

CategoryThree : Total $2200 第三类:总计$ 2200

and so on.... 等等....

which is the right rails way query (active record)? 哪个是正确的方法查询(活动记录)? and how to show the results in view? 以及如何在视图中显示结果? thanks 谢谢

You can calculate the combined total s of a category's sales by using ActiveRecord's #sum : 你可以计算组合total通过使用ActiveRecord的类别的销售额第#sum

category = Category.last
category.sales.sum(:total)

To render the sales totals in your views, you can do something like this: 要在您的视图中呈现销售总额,您可以执行以下操作:

In the category model: 在类别模型中:

# app/models/category.rb
class Category < ApplicationRecord
  def sales_total
    sales.sum(:total)
  end
end

In your relevant controller action: 在您相关的控制器操作中:

# app/controllers/categories_controller.rb
@categories = Category.includes(:sales)

And in the corresponding view: 并在相应的视图中:

<% @categories.each do |c| %>
  <%= "Category #{c.name}: Total $#{c.sales_total} %>
<% end %>

Hope this helps! 希望这可以帮助!

def sales_total_on(date)
  sales.where(date: date).sum(:total)
end

You can pass the date through the request parameters from a form to a controller. 您可以通过请求参数将日期从表单传递到控制器。 You could use a select or a datepicker. 您可以使用选择或日期选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM