获得关系的百分比

时间:2015-07-06 20:58:48

标签: ruby-on-rails postgresql

订单包含许多line_items,而后者又有employee_idamount_cents。在此查询的第二行中,我尝试通过收集具有特定line_item_perc的所有line_items并将其employee_id除以所有其他amounts_cents来创建line_items变量}}:

Order.joins(:tips, :line_items)
.select('line_items WHERE(custom_attributes -> "employee_id" = ?) AS employee_line_items,
  SUM(employee_line_items.amount_cents) / SUM(line_items.amount_cents) AS line_item_perc',
  params[:employee_id])
.sum('tips.amount_cents * line_item_perc')

不幸的是,这不起作用。 select语句甚至不会出现在最终的SQL中。 (我假设这是因为sum会覆盖它。)那么我还能做些什么才能获得line_item_perc

1 个答案:

答案 0 :(得分:0)

def line_item_percent(employee_id, line_item_id)
  total_amount_in_cents = Order.joins(:line_items).where("employee_id = ?", employee_id).pluck(:amount_cents).sum
  line_item_cents = LineItem.find(line_item_id).amount_cents
  answer = line_item_cents / total_amount_in_cents
end #returns decimal

试试这个。使用rails而不是SQL,它是否已经脱颖而出。