Random Guy Random Guy - 1 year ago 56
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 :


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download