You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rails的PlaceOwner模型中编写Scope获取无归属的Place

解决方案

要在PlaceOwner模型中编写scope获取所有没有所有者的Place,可以利用Rails内置查询方法实现,无需手动编写复杂SQL:

class PlaceOwner < ApplicationRecord
  belongs_to :user
  belongs_to :place

  scope :places_without_owner, -> {
    Place.left_outer_joins(:place_owners).where(place_owners: { id: nil })
  }
end

逻辑说明

  • left_outer_joins(:place_owners):执行左外连接,将所有Place记录与对应的PlaceOwner记录关联,即使Place没有对应的PlaceOwner也会保留该记录。
  • where(place_owners: { id: nil }):筛选出PlaceOwner记录为空的Place,也就是没有所有者的Place。

补充:语义更清晰的实现方式

实际上,这类查询放在Place模型中逻辑更通顺,同样能满足需求:

class Place < ApplicationRecord
  has_many :place_owners
  scope :without_owner, -> { left_outer_joins(:place_owners).where(place_owners: { id: nil }) }
end

调用时直接使用Place.without_owner即可获取目标结果。

验证示例

针对你给出的场景:

  • Place表:House13、House14、House15
  • PlaceOwner表:House13-User1、House14-User2
    调用PlaceOwner.places_without_owner(或Place.without_owner)会返回House15,符合预期。

内容的提问来源于stack exchange,提问作者Ezath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:05:22