新手问题 关于 RSpec 的一个问题

novtopro · September 11, 2015 · Last by novtopro replied at September 13, 2015 · 2098 hits
2 Floor has deleted

tasks.to_a.sum(&:points_toward_velocity) 转为 array

@zhenning 谢谢你,不过这是为什么呢?

#5 楼 @novtopro tasks 本身是一个数据库请求,数据库请求上的 #sum 是执行 SQL 语句中的 SUM() 函数。 如果你的 points_toward_velocity 是一个数据库字段,那么这样执行是没问题的。 但如果是一个对象的方法的话, ActiveRecord::Calculations#sum 就没办法执行了,因为没法把这个调用转写成 SQL 语句。 所以需要手动通过 to_a先执行这个 SQL 语句,然后变成对结果数组执行 Enumerable#sum 了,这样就对了。

#6 楼 @msg7086 那 tasks.all.sum ... 呢?

You need to Sign in before reply, if you don't have an account, please Sign up first.