views:

118

answers:

1

I am having great difficulty reading the API for named scopes. Each "bid" has a user_id and an auction_id. I need a scope to return the auctions the user has bid on.

Auction

class Auction < ActiveRecord::Base

  has_many :bids

  named_scope :current, lambda { 
    {:conditions => ["scheduled_start < ?", 0.minutes.ago], 
                      :order => 'scheduled_start asc'} 
  }

  named_scope :scheduled, lambda { 
    {:conditions => ["scheduled_start > ?", 0.minutes.ago], 
                      :order => 'scheduled_start asc'} 
  }

end

Bid

class Bid < ActiveRecord::Base
  belongs_to :user
  belongs_to :auction

  validates_numericality_of :point, :on => :create

 #
 # how do I write a named scope to check if a user has bid on an auction?

end
+1  A: 

you might wanna try a has many through association instead of a named scope.

class User < ActiveRecord::Base
  has_many :bids
  has_many :auctions, :through => :bids
end

Or do it the other way round

class Auction < ActiveRecord::Base
  has_many :bids
  has_many :users, :through => :bids
end

That way, you can simply write: @auction.users.include?(user)

That is not very clear to read, so lets improve it:

class Auction < ActiveRecord::Base
  has_many :bids
  has_many :bidders, :through => :bids, :source => :user
end

And now: @auction.bidders.include?(user)

Lastly, you can pass more than one param to a lamda, so (not the best example)

named_scope :for_apple_and_banana, lambda{|apple_id, banana_id| {:conditions => ["apple_id = ? AND banana_id = ?", apple_id, banana_id ]}}
Kafka