2008-12-26 45 views
2

我很难读取命名作用域的API。每个“出价”都有一个user_id和一个auction_id。我需要一个范围来返回用户已经出价的拍卖。命名作用域的API

拍卖

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 

投标

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 

回答

2

你可能会想尝试一个具有通过关联的,而不是一个命名范围多。

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

或做它的其他方式轮

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

这样的话,你可以简单的写:@ auction.users.include(用户)

不是很清楚阅读? ,所以让我们改进:

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

现在?:@ auction.bidders.include(用户)

最后,您可以通过一个以上的参数去一个LAMDA,所以(不是最好的例子)

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