Rails 3 ActiveRecord related native methods

If I have an auction record in which there are many offers related to it, I can do things like:

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

But if I want to make it more understandable (since it is used in several areas of the code), where would I define the method:

 highest_bid = auction.bids.highest_bid 

Is this possible, or do I need to refuse to search for it directly from the Bid class?

 highest_bid = Bid.highest_on(auction) 
+4
source share
2 answers

Sorry, I figured it out. I tried to add a method to the Bid ActiveRecord class, but I forgot to make it a class method so that it does not see this method.

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

Not 100% that this will handle the connection. Just write some tests for this now.

EDIT:

A quick test seems to show that it seems to magically handle associations.

 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 will find a bid for $ 50 if it does not contact correctly. Voodoo;)

+4
source

I think you would need to make the 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 
+1
source

All Articles