Selecting entries through a join table in Ruby on Rails

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 collections that do not belong to this gallery?

My knowledge of SQL is only rudimentary. I also want Rails (2.3) to do the job without an explicit SQL statement.

+3
source share
1 answer

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

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:

Collection.presentations_gallery_id_is_not(gallery_to_exclude.id).all
+1
source

Source: https://habr.com/ru/post/1765419/


All Articles