在rails中编写命名范围

时间:2011-12-16 03:44:41

标签: ruby-on-rails-3 named-scope

我有三种型号:产品,展示位置,收藏品

我正在尝试编写一个只选择不在某个集合中的产品的名称范围。

products has_many :collections, :through => :placements

collections has_many :products, :through => :placements

我到目前为止:

scope :not_in_front, joins(:collections).where('collections.id IS NOT ?', 4)

但这与我在查询中的预期相反:

Product Load (0.3ms)  SELECT "products".* FROM "products" INNER JOIN "placements" ON "products"."id" = "placements"."product_id" WHERE "placements"."collection_id" = 4

任何想法如何写这个只选择那个特定集合中没有的产品?

2 个答案:

答案 0 :(得分:0)

而不是collections.id IS NOT 4尝试collections.id != 4

答案 1 :(得分:0)

指定的范围变得太丑了,所以我选择了这个。不确定这是最好的方式,但是,它有效...

  def self.not_on_top_shelf  
    top_shelf = Collection.find_by_handle('top-shelf')
    products = Product.find(:all, :order => "factor_score DESC")
    not_on_top_shelf = products.map {|p| p unless p.collections.include?(top_shelf)}
    not_on_top_shelf.compact #some products may not be in a collection
  end