简体   繁体   中英

sum up amount of entries in a table in Ruby on Rails

I've got a table that looks like this

在此处输入图片说明

I want to display the amount of entries by a certain agent. I know I can use eg

orders.sum(:demand)

to sum up the demand. (table is called orders) However, there has to be a way to sum up the entries right? Eg for agent 1, this would be 4, for agent 2 it would be 1 and for agent 3 it would be 4 entries (as can be seen in the screenshot).

Any ideas?

If I understood correctly, what you need is the amount of entries by :agent_id , this should work:

Order.group(:agent_id).count

And the result is

=> {1=>4, 2=>2, 3=>3}

Edit:

If what you need is the count of the current_user :

Order.where(agent_id: @current_user).count

So if current_user is '1', you get:

=> 4

假设“确定”,您正在向控制器发送某种请求,并指定要查询的代理...

Order.where(agent_id: params[:agent_id]).count

With activerecord you can use the count method for counting the results.

Order.count # => 9

With the group method you can group the results by another column.

Order.group(:agent_id) # => #<ActiveRecord::Relation [ ... ] > 

Together you can get the results you want:

Order.group(:agent_id).count # => {1: 4, 2: 2, 3: 3}

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