简体   繁体   中英

What is the best way for getting difference between records' column

I have a model CounterRecord and column there data . Records list:

r1.data = 10
r2.data = 12
r3.data = 15
r4.data = 20

I would like to get differences between current and previous record [10,2,3,5] . Does Rails have default way do that?

我不认为RailsActiveRecord有这样的东西,但是只需一点点红宝石就可以轻松实现:

CounterRecord.pluck(:data).each_with_index.map { |c,i| a[0] == c ? c : (a[i-1].to_i - c).abs }

Do the rails have default way do that?

No.


Possible solution:

CounterRecord.pluck(:data).each_cons(2).map { |first, second| second - first }

NOTE: with big amount of records this will easily kill your memory.

没有默认的方法可以这样做。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM