Rails ActiveRecord查询选择总和

时间:2015-07-25 01:16:20

标签: ruby-on-rails activerecord sum

我有一个复杂的查询来计算对象关系特征的权重之和(对于PosgreSQL)

    private void ClearOilLube
    {
        set {oilChangeCheckBox.Checked = false;
        lubeJobCheckBox.Checked = false;}
    }

    private void ClearFlushes
    {
        set {radiatorFlushCheckBox.Checked = false; 
        transFlushCheckBox.Checked = false;}
    }

    private void ClearMisc
    {
        set {inspectionCheckBox.Checked = false;
        replaceMufflerCheckBox.Checked = false;
        tireRotationCheckBox.Checked = false;}
    }

    private void ClearOther
    {
        set {partsCostInputTextBox.Text = null;
        laborInputTextBox.Text = null;}
    }

    private void ClearFees
    {
        set {servicesLaborDispLabel.Text = null;
        partsDispLabel.Text = null;
        partsTaxDispLabel.Text = null;
        totalFeesDispLabel.Text = null;}
    }

理想情况下,我想为每个对象提取权重总和

1 个答案:

答案 0 :(得分:4)

由于pluck的参数实际上取代了生成的查询中的SELECT子句,因此只需a)将.select()调用移动到链的末尾即可完成此操作。将其更改为.pluck()。例如,以下内容适用于快速演示应用程序:

irb> User.group("name").order("SUM(age) DESC").pluck("name, SUM(age)")
   (1.0ms)  SELECT name, SUM(age) FROM "users" GROUP BY "users"."name"  ORDER BY SUM(age) DESC
=> [["rob2", 13], ["rob4", 5], ["rob", 1]]

任何joinswhere条款也应该有用。