sql - ActiveRecord find records from association with no associations -


i have simple many-to-many relation between 2 models , join table. in rails controller, have activerecord::relation object called job_descriptions initialized jobdescription.all , passed through flow controls apply additional where statements. here models:

class jobdescription < activerecord::base     has_many :job_description_experience_levels     has_many :experience_levels, through: :job_description_experience_levels end  class jobdescriptionexperiencelevel < activerecord::base     belongs_to :job_description     belongs_to :experience_level end  class experiencelevel < activerecord::base     has_many :job_description_experience_levels     has_many :job_descriptions, through: :job_description_experience_levels end 

i'm trying write query job_descriptions select instances not have experience_level association. how can this?

i've tried variations of ob_descriptions.includes(:job_descriptions).where(job_description_experience_levels: {job_description_id: nil}) , job_descriptions.where('id not in (select distinct(job_description_id) job_description_experience_levels)') without success.

most of resoures i've been able find on subject work calling query on model (e.g. jobdescription.where(something)) rather on existing relation object.

thanks!

edit #1

i managed solve on own before madyrockss answer, think answer more semantic solution. here solution anyways in case helps down line.

job_descriptions_with_experience_levels = job_descriptions.joins(:experience_levels) job_descriptions = job_descriptions - job_descriptions_with_experience_levels 

it works finding job_descriptions experience_levels , subtracting relation job_descriptions ones without experience_levels.

if job_description not have experience_level there no entry present job_description in job_description_experience_levels table. can following :

job_desc_ids_with_exp_level = jobdescriptionexperiencelevel.pluck(:job_description_id).uniq  job_descriptions = job_descriptions.where.not(id: job_desc_ids_with_exp_level) 

Comments