Get objects from sql which have no associated objects with specific field value

75 Views Asked by At

I have Job and Feedback models.

They are associated like this:

Job has_many :feedbacks Feedback belongs_to :job

I'm trying to make a query to get jobs which have NO feedbacks with feedback.user_id == job.client_id

4

There are 4 best solutions below

1
On
 jobs=Job.find(:all, :select => 'DISTINCT id', :order=>"id asc").map { |n| n.id.to_s })
 feedbacks=Feedback.find(:all, :select => 'DISTINCT job_id', :order=>"job_id asc").map { |n| n.job_id.to_s })
 jobs_without_feedbacks=jobs-feedbacks

ok. then try this. it might work good in your case. jobs_without_feedbacks will be the array of ids of the job with no feedback.

6
On

This uses two queries, but the pluck should be relatively light.

Job.includes(:feedbacks)
  .where(feedbacks: {id: nil})
  .where.not(client_id: Feedback.pluck(:user_id))
1
On
jobs=Job.all
no_feedback_jobs=Array.new
jobs.each do |job|{ (no_feedback_jobs<< job) if !job.feedback}

Try this .It will work fine

7
On
feedbacks = Feedback.map(&:user_id).uniq

User.includes(:jobs => :feedbacks).where.not(:client_id => feedbacks).where(:id => current_user.id)

Try this