简体   繁体   English

从联接表Ruby on Rails中关联的表中汇总数据

[英]Summing up data from tables that is associated in join table Ruby on Rails

I would like to ask how am I going to get the sum of material quantity in join table on every lot within a block. 我想问一下如何在一个区块中的每个批次上获取join table 的物料数量总和

The requirementalizes table has "quantity" column within. 需求表中包含"quantity"列。

For example.. 例如..

A Block has 3 lots, each lot is associated with requirement to have materials. 一个块有3个批次,每个批次与具有物料的要求相关。
Each Lot has... 每批都有...
material x- 200 材料x- 200
material y- 250 材质y- 250

How will I sum up the quantity for every material to have for Block. 我将如何汇总Block的每种物料的数量。
Block will have... 块会...
material x- 600 材料x- 600
material y- 750 材质y- 750

this is how my model association structured 这就是我的模型关联的结构

class Block < ApplicationRecord
  has_many :lots
end

class Lot < ApplicationRecord
  belongs_to :block
  belongs_to :requirement
end

class Requirement < ApplicationRecord
  has_many :requirementalizes
  has_many :materials, through: :requirementalizes
  belongs_to :lot
end

class Requirementalize < ApplicationRecord
  belongs_to :requirement
  belongs_to :material
end

class Material < ApplicationRecord
  has_one :requirementalize
  has_many :requirements, through: :requirementalize
end

Any help would be appreciated. 任何帮助,将不胜感激。

You could use ActiveRecord::Calculations sum 您可以使用ActiveRecord :: Calculations和

Just a quick example, You get the associated record you are looking for and call @something.sum(:quantity) 只是一个简单的例子,您获得了要查找的关联记录并调用@ something.sum(:quantity)

Here is an example using rails console. 这是使用Rails控制台的示例。 Just to give an idea of what is going on. 只是为了说明发生了什么。

2.3.3 :009 > total = Block.find(1).lots
...
#records found
...
2.3.3 :010 > total.sum(:quantity)
   (20.7ms)  SELECT SUM(`lots`.`quantity`) FROM `lots` WHERE `lots`.`block_id` = 1
 => 1205 #or some number

Reference: http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-sum 参考: http : //api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-sum

Thanks to Bryan Bibat. 感谢Bryan Bibat。 He helped me to solve this problem. 他帮助我解决了这个问题。

This is the solution to my problem. 这是我的问题的解决方案。

Block.each do |block|
  materials = block.lots.joins(requirement: :materials).group("materials.name").sum(:quantity)
  @blocks << { Block: block.block_no, Materials: materials }
end

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

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