views:

30

answers:

2

If I have an Auction record, which has many Bids associated with it, out of the box I can do things like:

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

But if I want to make this clearer (since it's used in multiple areas in the code), where would I define the method:

highest_bid = auction.bids.highest_bid

Is this actually possible or do I have to drop down to looking it up from the Bid class directly?

highest_bid = Bid.highest_on(auction)
+1  A: 

I think you would have to make a highest_bid method in your Auction model.

class Auction < ActiveRecord::Base
  has_many :bids

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

highest_bid = auction.highest_bid
captaintokyo
+1  A: 

Sorry, I figured this out. I had tried adding the method to the ActiveRecord Bid class, but I'd forgotten to make it a class method so it wasn't seeing the method.

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

Not 100% that this will handle the association however. Just writing some tests for this now.

EDIT:

A quick test seems to show that this seems to magically handle associations too.

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

The test would find the $50 bid if it wasn't associating correctly. Voodoo ;)

d11wtq
This will give you the highest bid, regardless of the auction. If you add the method to the Auction model you can get the highest bid per auction.
captaintokyo
I can confirm that this does seem to correctly associate with the Auction when invoked via auction.bids.
d11wtq
According to my tests, you are wrong:
d11wtq
Just realised you'll probably be wondering what all those `install_fixture` lines are in my tests. They just create records on demand rather than having a bunch of fixture SQL run on each test.
d11wtq
Hm, interesting, didn't know this was possible... firing up `rails console` and trying it myself ;-)
captaintokyo
I really *does* work! Magic! :-)
captaintokyo