2013-04-13 59 views
1

任何人都可以请看看我做错了什么吗? 它的Rails 3:范围Lambda错误的参数数

class Ad < ActiveRecord::Base 
belongs_to :postingtemplate 

    scope :active, (lambda do |ad| 
     Item.exists?(:postingtemplate => ad.postingtemplate_id) 
    end) 

end 

它的广告模型内的范围,应该返回所有的广告,其产品存在其中item.postingtemplate == ad.postingtemplate_id

UPDATE

打破了它分成两个范围和它的工作:)

class Ad < ActiveRecord::Base 
    belongs_to :postingtemplate 
    scope :active, where(:postingtemplate_id => Postingtemplate.active) 
end 

class Postingtemplate < ActiveRecord::Base 
    has_many :ads 
    scope :active, where(:id => Item.all.collect{|x| x.postingtemplate}.uniq) 
end 

如果有谁知道一个更好的方式 - 随时告诉

回答

0

您可以用join

scope :active, lambda { |ad| joins(:postingtemplate => :items).where(:postingtemplate => {:postingtemplate_id => ad.postingtemplate_id}) } 

做到这一点也许这将工作太:

scope :active, lambda { |ad| joins(:postingtemplate => :items).where(:postingtemplate => ad.postingtemplate) } 
+0

奇怪的是,他们都给予了同样的错误:'引发ArgumentError:错误的参数数目(0 1) '。有可能我应该使用别的东西而不是“哪里”部分? –

+0

你能告诉我们你是如何调用这个范围的吗?你是否传递了该呼叫的任何参数。请粘贴在你要调用的范围 – manoj

+0

的行中哦,我明白了:)就是这样调用它:'Ad.active'。没关系 - 找到另一种方式 –