在活动记录中乘列?

时间:2019-04-06 17:24:08

标签: ruby-on-rails activerecord

具有以下sql查询,如何转换Active Record中两列的乘法?

SELECT plan_name, plan_price, count(plan_id), plan_price*count(plan_id) AS totalrevenue
FROM leads
INNER JOIN plans p ON leads.plan_id = p.id
WHERE lead_status_id = 5
GROUP BY plan_name, plan_price;

1 个答案:

答案 0 :(得分:0)

我会尝试这样的事情。

leads = Lead.joins(:plans).
    where(lead_status_id: 5).
    group(:plan_name, :plan_price).
    select('plan_name, plan_price, count(plan_id), plan_price * count(plan_id) AS totalrevenue')

leads.each { |lead| puts lead.totalrevenue }

注意:

  1. 我不知道它是joins(:plan)还是joins(:plans),这取决于您的关联
  2. 如果您甚至需要打电话给plan_id,我都会在该字段中甚至给一个名字
  3. 如果打印整个对象,则不会替换totalrevenue之类的字段,因为它不是对象的一部分,而是虚拟属性