2010-10-18 53 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 
相关问题