![](/img/trans.png)
[英]ActiveRecord where statement either NOT IN (?), or doesn't exist
[英]ActiveRecord Query where field doesn't exist on model
我正在尝试编写一些复杂的查询。
我想找到所有具有负余额的Order
,但是balance不是Order
上的一个字段,它是Order
类中调用其他三种方法调用其他方法的方法,最后调用了大约5个类,在SQL中执行此操作或编写长AR查询非常困难。
有没有办法获得结果而不拉动记录并循环它们,并且没有重新实现构建订单余额的每个方法?
作为参考,我现在这样做:
negative_balances = []
Order.find_each {|o| negative_balances << o if o.balance > 0}
@negative_balances = negative_balances.group_by {|o| o.created_at.to_date}
和平衡看起来像这样:
class Order < AR::Base
def balance
total - (charge_payment + credit_payment)
end
end
您可以在SQL中进行加法和减法。 假设total
, charge_payment
和credit_payment
都是orders表上的整数列,那么:
Order.where("(total - (charge_payment + credit_payment)) < 0")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.