views:

22

answers:

1

I have three models

class Collection < ActiveRecord::Base
  has_many :presentations
  has_many :galleries, :through => :presentations
end

class Gallery < ActiveRecord::Base    
  has_many :presentations
  has_many :collections, :through => :presentations
end

class Presentation < ActiveRecord::Base
  belongs_to :collection
  belongs_to :gallery 
end

How do I get all the collections that do not belong to a given gallery?

My SQL knowledge is only rudimentary. I also want to let Rails (2.3) do the work without using explicitly a SQL expression.

+1  A: 

Out of the box, you technically have to write some SQL (where clause)...

gallery_to_exclude = Gallery.first
Collection.find(:all,
  :include => :presentations,
  :conditions => ['presentations.gallery_id IS NULL OR presentations.gallery_id != ?',
                   gallery_to_exclude.id])

If you want to use Searchlogic, you can avoid this, though:

Collection.presentations_gallery_id_is_not(gallery_to_exclude.id).all
Dave Pirotte
Thanks, that works. But only for collections that have a gallery. What about the collections that have no gallery? (collection.galleries.length == 0)
neo
I edited the above to show collections without galleries. (the #find, not the searchlogic method)
Dave Pirotte