简体   繁体   English

ActiveRecord查询模型上不存在字段的位置

[英]ActiveRecord Query where field doesn't exist on model

I have a bit of a complex query I'm trying to write. 我正在尝试编写一些复杂的查询。

I want to find all Order s that have a negative balance, but balance isn't a field on Order it's a method in the Order class that calls three other methods that call other methods, and by the end, about 5 classes are called, making doing this in SQL or writing a long AR query very difficult. 我想找到所有具有负余额的Order ,但是balance不是Order上的一个字段,它是Order类中调用其他三种方法调用其他方法的方法,最后调用了大约5个类,在SQL中执行此操作或编写长AR查询非常困难。

Is there a way to get the result without pulling the records and looping over them, and without reimplementing each method that builds the order balance? 有没有办法获得结果而不拉动记录并循环它们,并且没有重新实现构建订单余额的每个方法?

For reference, I'm doing it like this right now: 作为参考,我现在这样做:

    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}

and balance looks like this: 和平衡看起来像这样:

class Order < AR::Base
  def balance
    total - (charge_payment + credit_payment)
  end
end

You can do addition and subtraction in SQL. 您可以在SQL中进行加法和减法。 Assuming total , charge_payment , and credit_payment are all integer columns on the orders table, then: 假设totalcharge_paymentcredit_payment都是orders表上的整数列,那么:

Order.where("(total - (charge_payment + credit_payment)) < 0")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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