2

I have two models, ParentProfile and RoomParentAssignment:

class ParentProfile < ActiveRecord::Base
  has_many :room_parent_assignments

and

class RoomParentAssignment < ActiveRecord::Base
  belongs_to :room_parent_profile, class_name: 'ParentProfile', foreign_key: 'parent_profile_id'

I would like to retrieve all ParentProfile records where there are no room_parent_assignments. I'm looking for something like the following statement (which needless to say, is invalid):

@non_room_parents = ParentProfile.where(!room_parent_assignments.present?)

How would I do this?

tobogranyte
  • 899
  • 1
  • 9
  • 26
  • Possible duplicate of [Deleting VS Finding Orphans using ActiveRecord helpers](http://stackoverflow.com/questions/33180042/deleting-vs-finding-orphans-using-activerecord-helpers) – D-side Oct 27 '15 at 13:17

3 Answers3

2

The below query should do

ParentProfile.joins("left outer join room_parent_assignments on room_parent_assignments.parent_profile_id = parent_profiles.id").where(room_parent_assignments: {parent_profile_id: nil})
Pavan
  • 33,316
  • 7
  • 50
  • 76
1

use the below code:

parent_ids = RoomParentAssignment.select(parent_profile_id)

@non_room_parents = ParentProfile.where.not(:id => parent_ids)
Pavan
  • 33,316
  • 7
  • 50
  • 76
Chakreshwar Sharma
  • 2,571
  • 1
  • 11
  • 35
0

You have two options here:

OPTION 1

@non_room_parents = ParentProfile.where.not(id: RoomParentAssignment.all.map(&:parent_profile_id))

OPTION 2

@non_room_parents = ParentProfile.where("id NOT IN (?)", RoomParentAssignment.all.map(&:parent_profile_id))

Both of them are equal to get no parent rooms.

akbarbin
  • 4,985
  • 1
  • 28
  • 31
  • `RoomParentAssignment.map` generates the following error: NoMethodError: undefined method `map' for #. Changing it to RoomParentAsssignment.all.map seems to work correctly. – tobogranyte Oct 27 '15 at 21:42