2014-01-23 112 views
0

我有一個在Rails 4項目中設置像這樣的幾個模型。有條件似乎去評估

student.rb

class Student < ActiveRecord::Base 
    has_many :contracts 

    def balance 
    unpaid_contracts.sum(&:sum_total) 
    end 

private 

    def unpaid_contracts 
    unpaid_contracts = [] 
    contracts.each do |c| 
     unpaid_contracts << c if c.unpaid? # This is the problem 
    end 
    end 

end 

contract.rb

class Contract < ActiveRecord::Base 

    has_many :invoices, dependent: :destroy 
    belongs_to :student 

    def unpaid? 
    return true if invoices.blank? 
    invoices.each do |i| 
     return true if i.current_status != "paid" && i.current_status != "rescinded" 
    end 
    end 
end 

無論我做什麼所有的合同被添加到unpaid_contracts。在db中根本沒有發票,所以我會假設unpaid?應該總是評估爲真,對不對?

事實上,即使我將條件更改爲unpaid_contracts << c if false問題仍然存在。

+0

您是否嘗試過加載合同並使用'.unpaid?'它返回什麼? – meagar

回答

1

注意你的返回值:

def unpaid_contracts 
    unpaid_contracts = [] 
    contracts.each do |c| 
     unpaid_contracts << c if c.unpaid? # This is the problem 
    end 
    end 

你返回contracts.each,這是說所有合同,不unpaid_contracts

這將修復它...

def unpaid_contracts 
    unpaid_contracts = [] 
    contracts.each do |c| 
     unpaid_contracts << c if c.unpaid? # This is the problem 
    end 
    unpaid_contracts 
    end 

但是,這是更好的:

def unpaid_contracts 
    contracts.select(&:unpaid?) 
    end 
1

你可以試試下面的

  1. 私有方法只有你當不打算使用Class或Class的一個實例,所以試着把它拿出來。

  2. 編碼它的稍微更合適的方法:

    def unpaid_contracts 
        contracts.select { |contract| contract.invoices.count == 0} 
    end 
    
  3. 正如@meagar提到的,你是不是返回正確的變量。

+0

這段代碼似乎對我很有用,就像'contracts.select {| contract | contract.pending? }' 感謝您的私人方法! – niftygrifty

+0

不客氣! –