我想找到拍卖中的最高出价。在拍卖控制器中,我执行以下操作:首先,我想通过 ID 检索出价模型的所有出价,然后我想对结果进行降序排序,并选择第一个(=应该是最高出价):
@highest_bid = Bid.find_by_auction_id(params[:id]).order("amount DESC").first
抛出此错误:
NoMethodError in AuctionsController#show undefined method `order' for #<Bid:0x98e52e8>
提取的源代码(第 11 行附近):
@auction = Auction.find(params[:id])
@seller = User.find(@auction.user_id)
@highest_bid = Bid.find_by_auction_id(params[:id]).order("amount DESC").first
您仅在
ActiveRecord::Relation类上有
order
方法,而 find_*
操作返回 ActiveRecord::Base (Bid
,在您的情况下)。
您应该像这样重写您的查询:
@highest_bid = Bid.where(auction_id: params[:id]).order("amount DESC").limit(1).first
find_by_auction_id
返回单个 Bid
对象,您不能在其上调用 order
。你应该这样做:
@higheset_bid = @auction.bids.order('amount DESC').first
如果没有的话,您应该在
has_many :bids
模型中创建 Auction
关联。