计算总的运行轨道3 [英] Calculate running total rails 3

查看:135
本文介绍了计算总的运行轨道3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的方式 - 或者更确切地说,任何方式 - 来计算总运行Rails中?

What's the best way - or, indeed, any way - to calculate a running total in Rails?

我有一个模型,销售。它有一个量列和sales_value列。我需要填充第三列,total_quantity,随着previous记录的数量值,当表由isbn_id分类的总和,那么CHANNEL_ID,然后invoice_date。这台各种合理的数据库管理敲响了警钟,所以我想知道如果它甚至有可能。

I have a model, Sale. It has a quantity column and a sales_value column. I need to populate a third column, total_quantity, with the sum of the quantity values of the previous records, when the table is sorted by isbn_id, then channel_id, then invoice_date. This sets all sorts of sensible database management alarm bells ringing, so I'm wondering if it's even possible.

的原因需要这个累计总和是一个百分比应用于销售,其中的累积量是在特定范围内。我不能在所有的记录,使用平均销售值,因为销售保证金可随时间变化很大 - 所以我的平均应用到了一堆销售可能高于或低于工资提成收款人。

The reason for needing this cumulative sum is to apply a percentage to the sales where the cumulative quantity is within a particular range. I can't use an average sales value across all records, because the margin on sales can vary dramatically over time - so I'd apply an average to a bunch of sales which might over or under pay the royalty payee.

所以。我应该做销售模型before_save回调,并update_attribute,不知何故?是否有返回表格时以特定方式排序的previous记录的值的方法?或者我应该转储全部销售记录到一个数组,也许还可以利用注入积累运行总?

So. Should I do a before_save callback on the Sale model, and update_attribute, somehow? Is there a method to return the value of the previous record when the table is sorted in a particular way? Or should I dump all Sale records into an array and maybe use inject to accumulate the running total?

任何想法非常受欢迎,在此先感谢。

Any ideas most welcome, thanks in advance.

更新:后续问题问这里

推荐答案

不要使用注射(srsly)。要做到这一点,最好的方法是使用SQL命令组和/或计算中的ActiveRecord(如总和)方法

Do not use inject (srsly). The best way to do this is to use the SQL group commands and/or the Calculations methods in activerecord (like sum)

http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ ClassMethods.html

这篇关于计算总的运行轨道3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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