Search code examples
ruby-on-rails-3named-scope

Writing a named scope in rails


I have three models: Products, Placements, Collections

I'm trying to write a name scope that only chooses products NOT in a certain collection.

products has_many :collections, :through => :placements

collections has_many :products, :through => :placements

I got about this far:

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

But that generated the opposite of what I expected in the query:

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

Any idea how to write this to only select the products not in that particular collection?


Solution

  • The named scope was getting too ugly, so I went with this. Not sure it's the best way, but, it works...

      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