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
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.
jobs without ANY feedbacks. I need jobs without feedbacks with user_id == job.client_id. If job has feedbacks with any other user_id – it's OK.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
feedbacks = Feedback.map(&:user_id).uniq
User.includes(:jobs => :feedbacks).where.not(:client_id => feedbacks).where(:id => current_user.id)
Try this
jobs_as_worker = current_user.jobs_as_worker.includes(:feedbacks).where{client_id.not_in Feedback.select{user_id}.uniq} This code works but not in the way I need. I need to use not all feedbacks in databse – Feedback.select{user_id}.uniq, but feedbacks only for a specific job, like jobs.feedbacks.select{user_id}.uniq – but I can't make this work.feedback.user_id == job.client_idjobs that belong to current_userThis 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))
.where(feedbacks: {id: nil}) means? How id could be nil?Job.includes(:feedbacks).where(feedbacks: {id: nil} returns jobs which do not have feedbacks..includes(:feedbacks).where(feedbacks: {id: nil}).where.not(feedbacks: {user_id: job.client_id}) – but I can't make it work.not to the last line?
jobs_as_worker = current_user.jobs_as_worker.includes(:feedbacks).where{client_id.not_in Feedback.select{user_id}.uniq}