嗨,斯塔克溢出队。
我正在使用rails,并试图找到代码,使用rails对同一列中的2条记录进行减法。
我有下表
customers
id num_hid num_oxi
1 1 2
2 3 4
3 5 6
4 7 8
我想得到这个结果
@result = last_num_hid_id_4 - last_num_hid_id_3
//calcultion is: 7-5 = 2
我完成了这段代码,但这显示了数组中的最后2条记录。
<% @customers.each.last(2) do |customer|%> %>
<%= customer.num_hid %>
<% end %>
我尝试了这段代码,但只显示了最后一条记录。
@last_customer =Customer.all.last
@last.num_hid
有人能帮我解决这个问题吗?
我将感谢你所有的评论。
提前谢谢。
发布于 2022-04-09 00:13:38
您可以像这样在模型中定义类方法
class Customer < ActiveRecord::Base
def self.subtraction(atr)
last[atr] - second_to_last[atr]
end
end
或更有效率
class Customer < ActiveRecord::Base
def self.subtraction(atr)
last(2).pluck(atr).reverse.inject(:-)
end
end
然后在模型作用域之后调用它。
例如
Customer.order(id: :desc).subtraction(:id)
# => -1 # if there is continuous sequence of ids
https://stackoverflow.com/questions/71804015
复制相似问题