如果我有一个拍卖记录,其中有很多与之相关的出价,我可以立即执行以下操作:
highest_bid = auction.bids.last(:all, :order => :amount)
但是如果我想让这个更清楚(因为它在代码的多个区域中使用),我应该在哪里定义方法:
highest_bid = auction.bids.highest_bid
这实际上是可能的还是我必须下拉才能直接从 Bid 类中查找?
highest_bid = Bid.highest_on(auction)
最佳答案
对不起,我想通了。我曾尝试将该方法添加到 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 美元的出价。巫毒教;)
关于ruby-on-rails - Rails 3 ActiveRecord 关联集合自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3959397/