2009-09-02 47 views
0

我的代碼存在一些問題。這可能是由於一些設計錯誤。我嘗試了幾件事情。這裏有兩個。如何使用ActiveRecord關聯獲取最近的單個項目?

問題:我有一個1 (lending) - N (contracts)的關係。我想致電lending.current_contract,這將返回最後一個相關合同。 優化也是一個問題。我想撥打:lending, :include => :contracts,而不必對包含所有合同的合同數組中已有的合同使用單獨的查詢。

壞的解決方案1:

has_one :current_contract, :class_name => "Contract" 

這並不工作,因爲我每次創建,更新或摧毀它具有更新父貸款也是如此。做到這一點,我得到一個回調混亂。例如,在創建貸款時,它也會創建第一個合同。出於某種原因,對於這兩種借貸都使用回調,因爲其合約不起作用。

爲溶液2:

def current_contract 
    return if contracts.relevant.empty? 
    @current_contract = contracts.relevant.last 
end 

發送一個副本,而不是參考。所以lending.current_contract.status = value不起作用。

是否有一些我應該看的設計模式?有沒有一些例子?我看過一些github項目,但沒有一個解決了類似的問題,因此我認爲這是一個設計問題。

回答

3

關聯通常可以採用:conditions散列,這可以很方便。 (而且我在半小時前直到需要時纔將它忘記)。

它會幫助嗎?喜歡的東西:

has_one :current_contract, :class_name => "Contract", :conditions => ... 

看着the book多一點(364頁,以準確):

has_one :current_contract, :class_name => "Contract", :order => 'created_at DESC' 

...這將參考最近創建的合同。當然,你可以有更合適的欄目。

我希望我能看到前面 - 我需要去改變現在一些代碼...

0

通過「相關」,你的意思最近?

class Lending < ActiveRecord::Base 
    has_many :contract 
    attr_reader :current_contract 

    def initialize 
    @current_contract = Contract.New 
    end 
    ... 
end 

class Contract < ActiveRecord::Base 
    has_one :lending 
    ... 

    def before_delete 
    # update lending to the most relevant contract 
    # if this is the current_contract for parent lending 
    end 
end 
相關問題