0

The following works, properly, but seems like I'm probably not utilizing something in rails that I should be. The working bit is:

MaxOffer.joins("JOIN items ON items.id = max_offers.item_id")
        .order('amount_in_cents desc')
        .where('items.id = 20')
        .limit(5).collect do |moffer|

At first I assumed I didn't have to explicitly use a join since the models are:

class MaxOffer < ActiveRecord::Base
  belongs_to :item
  belongs_to :user

class User < ActiveRecord::Base
  has_many :bids
  has_many :max_offers

But got errors when I tried to simply use item.id in the where clause. Is there a more proper way to do this, or is explicitly including the join necessary?

4

1 に答える 1

1

MaxOfferとItemの関係を考えると、これは機能するはずです。

MaxOffer.joins(:item)
    .where('items.id = ?', 20)
    .order('amount_in_cents desc')
    .limit(5).collect do |moffer|

両方を実行し、生成されたSQLを調べて、違いがあるかどうかを確認します。

于 2012-05-16T16:04:17.063 に答える