2010-10-18 49 views
4

如果我有一個拍賣紀錄,其中有許多與其相關的投標,開箱即用,我可以做這樣的事情的:Rails 3種中ActiveRecord的相關收藏品的定製方法

highest_bid = auction.bids.last(:all, :order => :amount) 

但是,如果我想使這個更清晰(因爲它在多個領域的二手代碼),我哪裏會定義方法:

highest_bid = auction.bids.highest_bid 

這實際上可能還是我必須下降到直接從Bid類尋找它?

highest_bid = Bid.highest_on(auction) 

回答

4

對不起,我想通了。我曾嘗試將該方法添加到ActiveRecord Bid類中,但我忘記將其設置爲類方法,因此它沒有看到該方法。

class Bid < ActiveRecord::Base 
    ... 
    def self.highest 
    last(:order => :amount) 
    end 

不是100%,但這將處理該關聯。現在就爲此寫一些測試。

編輯:

簡單的測試似乎表明,這似乎奇蹟般地處理關聯了。

test "highest bid finder associates with auction" do 
    auction1 = install_fixture :auction, :reserve => 10 
    auction2 = install_fixture :auction, :reserve => 10 

    install_fixture :bid, :auction => auction1, :amount => 20, :status => Bid::ACCEPTED 
    install_fixture :bid, :auction => auction1, :amount => 30, :status => Bid::ACCEPTED 
    install_fixture :bid, :auction => auction2, :amount => 50, :status => Bid::ACCEPTED 

    assert_equal 30, auction1.bids.highest.amount, "Highest bid should be $30" 
end 

如果測試未正確關聯,則會找到$ 50出價。巫術;)

+0

這會給你最高的出價,無論拍賣。如果您將方法添加到拍賣模型,您可以獲得每次拍賣的最高出價。 – Mischa 2010-10-18 13:38:00

+0

我可以確認這似乎與通過auction.bids調用時拍賣正確關聯。 – d11wtq 2010-10-18 13:42:53

+0

根據我的測試,你錯了: – d11wtq 2010-10-18 13:43:32

1

我認爲你將不得不作出一個highest_bid方法在Auction模型。

class Auction < ActiveRecord::Base 
    has_many :bids 

    def highest_bid 
    bids.last(:all, :order => :amount) 
    end 
end 

highest_bid = auction.highest_bid 
相關問題