简体   繁体   English

Ruby on Rails 3:如何通过关联的方法查找关联的记录?

[英]Ruby on Rails 3: How to find associated records through associated method?

I have Invoices with many Items and Payments. 我有很多项目和付款的发票。

This is my Invoice model (at least a part of it): 这是我的发票模型(至少是其中的一部分):

def total
  items.sum { |item| item.total }
end

def balance
  self.payments.sum(:amount) - self.total
end

Now in the Payment view I am trying to find all the Invoices with a balance less than 0: 现在,在“付款”视图中,我试图找到余额少于0的所有发票:

<%= f.select(:invoice_id, current_user.invoices.where("balance > ?", 0)) %>

This doesn't work of course, because balance is not a column. 当然这是行不通的,因为balance不是一列。 But how can I insert a method there? 但是,如何在其中插入方法?

Thanks for any help. 谢谢你的帮助。

You have a couple of options. 您有两种选择。 You could always make balance a column (updating it as appropriate when payments or items are added), which will allow you do this sort of query efficiently. 您始终可以使一列balance (在添加付款或项目时适当更新它),这将使您高效地进行这种查询。

You could, however, just use a plain Ruby approach - specifically, Array#select . 但是,您可以只使用简单的Ruby方法-具体地说就是Array#select Something like 就像是

current_user.invoices.to_a.select {|invoice| invoice.balance < 0}

would get you there. 会带你到那里。 It wouldn't be very efficient if users have a large number of invoices though. 但是,如果用户有大量发票,那将不是很有效。

Update : also, you're going to hit an N+1 query situation if you do it like this, because each invoice will need to retrieve its items and payments from the database. 更新 :同样,如果您这样做,您将遇到N + 1查询情况 ,因为每个发票都需要从数据库中检索其项目和付款。 To avoid this, you need to include the items and payments in the original query like so: 为了避免这种情况,您需要像这样在原始查询中包括物料和付款:

current_user.invoices.includes(:items, :payments).to_a.select{ ... }

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

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