使用ActiveRecord范围进行多列计算?

时间:2012-02-13 12:58:14

标签: ruby-on-rails ruby-on-rails-3 activerecord

我的ActiveRecord模型有两个数据库属性,totalprocessing_fees

它定义了各种范围,例如(仅作为示例):

class Item < ActiveRecord::Base
  scope :completed, joins(:order).where(:orders => {:status => Order::Status::COMPLETED})
  scope :for_client, lambda {|client| where("client_id=?", client.id)}
...etc...
end

我可以轻松地做一些事情:

Item.completed.for_client(client).sum(:total)

但我想做的是:

Item.completed.for_client(client).calculate(:total - :processing_fees) # obv not valid

有没有办法做这样的事情?

1 个答案:

答案 0 :(得分:6)

这样的事情应该有效:

Item.completed.for_client(client).calculate(:sum, "item.total - item.processing_fees")