命名范围的API

时间:2008-12-26 21:09:42

标签: ruby-on-rails

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

拍卖

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

1 个答案:

答案 0 :(得分: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?(user)

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

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 ]}}
相关问题