开发者

Selection of records through a join table in Ruby on Rails

开发者 https://www.devze.com 2023-01-16 12:15 出处:网络
I have three models class Collection < ActiveRecord::Base has_many :presentations has_many :galleries, :through => :presentations

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 usin开发者_开发百科g explicitly a SQL expression.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消