Ruby on rails 如何基于相关模型的存在检索ActiveRecord记录

Ruby on rails 如何基于相关模型的存在检索ActiveRecord记录,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我有两种型号,ParentProfile和RoomParentAssignment: class ParentProfile < ActiveRecord::Base has_many :room_parent_assignments 我该怎么做呢?下面的查询应该可以 ParentProfile.joins("left outer join room_parent_assignments on room_parent_assignments.parent_profile_id = p

我有两种型号,
ParentProfile
RoomParentAssignment

class ParentProfile < ActiveRecord::Base
  has_many :room_parent_assignments

我该怎么做呢?

下面的查询应该可以

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})
使用以下代码:

parent_ids = RoomParentAssignment.select(parent_profile_id)

@non_room_parents = ParentProfile.where.not(:id => parent_ids)

这里有两个选项:

选择1

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

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

它们都等于不获取父房间。

RoomParentAssignment的可能重复。map生成以下错误:NoMethodError:未定义的方法“map”用于#。将其更改为RoomParentAssignment.all.map似乎工作正常。
@non_room_parents = ParentProfile.where.not(id: RoomParentAssignment.all.map(&:parent_profile_id))
@non_room_parents = ParentProfile.where("id NOT IN (?)", RoomParentAssignment.all.map(&:parent_profile_id))