I have these 3 models.

class Ivr < ActiveRecord::Base

has_many :klusterings, :dependent => :destroy

has_many :klusters, :through => :klusterings, :uniq => true

end

class Kluster < ActiveRecord::Base

has_many :klusterings, :dependent => :destroy

has_many :ivrs, :through => :klusterings, :uniq => true

end

class Klustering < ActiveRecord::Base

belongs_to :kluster

belongs_to :ivr

end

I faced 2 problems and didn’t manage to find any good tutorial.

- Given some Kluster A, I want to find all the Ivrs that aren’t in A.
- I want to find all the Ivrs that aren’t in ANY Kluster.

– I managed to do 1. with:

@kluster = Kluster.find(params[:id])

@all_ivrs = Ivr.find(:all)

@ivrs = (@all_ivrs - @kluster.ivrs)

– And I did 2. with:

@all_ivrs = Ivr.find(:all).select{ |ivr| ivr.klusters.empty? }

But 1. does two SQL queries, one possibly very big (Ivr.find(:all)).

And 2. does that too.

Any way to do this, preferibly with dynamic finders?