点心多个列用ActiveRecord [英] Sum on multiple columns with Activerecord

查看:132
本文介绍了点心多个列用ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的ActiveRecord。我想要做的总和一个模范生的多列。我的模范学生就像是以下内容:

I am new to Activerecord. I want to do sum on multiple columns of a model Student. My model student is like following:

 class Student < ActiveRecord::Base
   attr_accessible :class, :roll_num, :total_mark, :marks_obtained, :section
 end

我想是这样的:

I want something like that:

 total_marks, total_marks_obtained = Student.where(:id=>student_id).sum(:total_mark, :marks_obtained)

但它给下面的错误。

But it is giving following error.

NoMethodError: undefined method `except' for :marks_obtained:Symbol

所以,我问我是否要查询模型两次针对上述情况,即一个以查询总分,另外找得到的痕迹。

So I am asking whether I have to query the model two times for the above, i.e. one to find total marks and another to find marks obtained.

推荐答案

您可以使用原始的SQL,如果你需要。事情是这样的,返回一个对象,你就必须提取值......我知道你指定活动记录!

You can use raw SQL if you need to. Something like this to return an object where you'll have to extract the values... I know you specify active record!

Student.select("SUM(students.total_mark) AS total_mark, SUM(students.marks_obtained) AS marks obtained").where(:id=>student_id)

有关导轨4.2(前面未选中)

For rails 4.2 (earlier unchecked)

Student.select("SUM(students.total_mark) AS total_mark, SUM(students.marks_obtained) AS marks obtained").where(:id=>student_id)[0]

注:下面的语句中的括号内。如果没有它的语句返回一个类:: ActiveRecord_Relation,而不是AR实例。什么是这个显著的是,你不能使用第一上的关系。

....where(:id=>student_id).first #=> PG::GroupingError: ERROR:  column "students.id" must appear in the GROUP BY clause or be used in an aggregate function

这篇关于点心多个列用ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆