【问题标题】:How to retrieve ActiveRecord records based on the presence of a related model如何根据相关模型的存在来检索 ActiveRecord 记录
【发布时间】:2015-10-28 10:07:41
【问题描述】:

我有两个模型,ParentProfileRoomParentAssignment

class ParentProfile < ActiveRecord::Base
  has_many :room_parent_assignments

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

我想检索所有有没有room_parent_assignmentsParentProfile记录。我正在寻找类似以下语句的内容(不用说,是无效的):

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

我该怎么做?

【问题讨论】:

标签: ruby-on-rails activerecord


【解决方案1】:

下面的查询应该做

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})

【讨论】:

    【解决方案2】:

    使用下面的代码:

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

    【讨论】:

      【解决方案3】:

      这里有两个选择:

      选项 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: undefined method `map' for #<0x007fdc9b4b5468>
      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多