代码之家  ›  专栏  ›  技术社区  ›  d11wtq Vadim Baryshev

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

  •  4
  • d11wtq Vadim Baryshev  · 技术社区  · 14 年前

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

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

    但是,如果我想更清楚地说明这一点(因为它在代码的多个区域中使用),我应该在哪里定义方法:

    highest_bid = auction.bids.highest_bid
    

    highest_bid = Bid.highest_on(auction)
    
    2 回复  |  直到 14 年前
        1
  •  4
  •   d11wtq Vadim Baryshev    14 年前

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

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

    但这并不是百分之百地处理关联。现在就写些测试。

    编辑:

    一个快速测试似乎表明,这似乎也神奇地处理了关联。

    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美元的出价。伏都教;)

        2
  •  1
  •   Mischa    14 年前

    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