在查询的地方使用自定义方法

时间:2018-03-21 15:46:44

标签: ruby-on-rails ruby-on-rails-4

我希望能够使用balance查询所有客户。我将余额定义为:

class Client < ActiveRecord::Base
    def balance
        purch = self.purchases.map(&:total).sum
        pay = self.payments.sum(:amount)
        return purch - pay
    end
end

class Purchase < ActiveRecord::Base
    def total
        total = self.weekly_cost * self.weeks
        total = total * discount/100.0 if discount.present? and discount > 0
        return total
    end
end

其中totalPurchase类上的方法,而不是purchases表上的列。我想在where查询中使用它,但显然以下内容不起作用,因为balance不是我桌子上的列:

Client.where("balance > ?", 0) 

这可能吗?

1 个答案:

答案 0 :(得分:1)

我建议将余额存储在数据库中,以便查询并显示它。如果您在应用上显示余额,则会浪费资源进行实时计算,而是存储它并节省资源,您的应用将更快。使用下一个示例:

class Client < ActiveRecord::Base
    has_many :purchases
    has_many :payments

    def update_balance
        new_balance = purchases.sum(:total) - payments.sum(:amount)
        update_attributes(:balance, new_balance)
    end
end

class Purchase < ActiveRecord::Base
    belongs_to :client

    # Use some callbacks to update the client balance after save the record
    after_save :calculate_total, :update_client_balance

    def calculate_total
      total = weekly_cost * weeks * ((discount || 100) / 100)
      # I use update_column to skip the callbacks and only store the value
      update_column(:total, total)
    end

    def update_client_balance
      client.update_balance if client
    end
end


class Payment < ActiveRecord::Base
    belongs_to :client
    # Use some callbacks to update the client balance after save the record
    after_save :update_client_balance

    def update_client_balance
      client.update_balance if client
    end
end

希望有所帮助