简体   繁体   中英

Rails 5 group by, sum and show in view

I have two models in Rails 5 and 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?

CategoryTwo : Total $4000

CategoryThree : Total $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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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