Random Guy Random Guy - 4 months ago 8
Ruby Question

Retrive records which are not referenced in other table, ActiveRecord query

There are 2 tables : User and Teacher. Teacher.user_id is from User. So, how do I find in a single query, all the users who are not in teachers.

I meant something along the lines :

User.not_in(Teacher.all)

Answer

You can use where.not query from ActiveRecord try something like below:

User.where.not(id: Teacher.pluck(:user_id).reject {|x| x.nil?})

Note: used reject method, in case you have nil values in some records.

Comments