Ruby on rails Rails 3 ActiveRecord关联的集合自定义方法

Ruby on rails Rails 3 ActiveRecord关联的集合自定义方法,ruby-on-rails,activerecord,ruby-on-rails-3,recordset,Ruby On Rails,Activerecord,Ruby On Rails 3,Recordset,如果我有一个拍卖记录,其中有许多与之相关的出价,我可以做一些开箱即用的事情,如: highest_bid = auction.bids.last(:all, :order => :amount) 但是,如果我想更清楚地说明这一点(因为它在代码的多个区域中使用),我将在哪里定义该方法: highest_bid = auction.bids.highest_bid 这实际上是可能的,还是我必须直接从Bid类中查找它 highest_bid = Bid.highest_on(auction)

如果我有一个拍卖记录,其中有许多与之相关的出价,我可以做一些开箱即用的事情,如:

highest_bid = auction.bids.last(:all, :order => :amount)
但是,如果我想更清楚地说明这一点(因为它在代码的多个区域中使用),我将在哪里定义该方法:

highest_bid = auction.bids.highest_bid
这实际上是可能的,还是我必须直接从Bid类中查找它

highest_bid = Bid.highest_on(auction)

我认为您必须在您的
拍卖
模型中采用
最高出价
方法

class Auction < ActiveRecord::Base
  has_many :bids

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

highest_bid = auction.highest_bid
类拍卖:金额)
结束
结束
最高出价=拍卖。最高出价

对不起,我想出来了。我曾尝试将该方法添加到ActiveRecord Bid类中,但我忘记将其设置为类方法,因此它看不到该方法

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

如果没有正确关联,测试将找到50美元的出价。伏都教;)

这将给你最高的出价,无论拍卖。如果将该方法添加到拍卖模型中,则每次拍卖都可以获得最高的出价。我可以确认,当通过Auction.bids调用时,这似乎与拍卖正确关联。刚刚意识到,您可能会想知道我的测试中所有的
install\u fixture
行都是什么。他们只是按需创建记录,而不是在每个测试上运行一堆fixture SQL。。。启动rails控制台并亲自尝试;-)
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