范围Lambda错误的参数数量

时间:2013-04-13 14:32:49

标签: ruby-on-rails

任何人都可以看看我做错了什么? 这是Rails 3:

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

更新

将其分为两个范围并且有效:)

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

如果有人知道更好的方式 - 随时告诉

1 个答案:

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