启用多对多API查询

问题描述 投票:0回答:1

情况

我有以下三种型号

class House < ApplicationRecord
  has_many :ownerships
  has_many :people, through: :ownerships
end
class Person < ApplicationRecord
  has_many :ownerships
  has_many :houses, through: :ownerships
end

class Ownership < ApplicationRecord
  belongs_to :house
  belongs_to :person
end

预期结果

[基本上,我想以JSON进行查询,以获取所有与houses相关联的people的列表。关键是有些房子没有人,有些人没有房子,因此Ownership关联没有所有房子的ID。如果房屋不属于任何人,则答复为零。

例如,查询结果如下:

{
  house1: {
    owners: [
      person1,
      person2
    ]
  },
  house2: {
    owners: null
  },
  house3: {
    owners: [
      person2
    ]
  }
}

我尝试过的

我尝试使用includes,但是我得到了没有相关结构的独立项目数组。

House.all.includes(:people).as_json(include: [:people])

但是people值在单独的键中,并且与houses不相关。

ruby-on-rails ruby many-to-many has-many-through
1个回答
2
投票

用于查询,您可以如下所示

House.includes(ownerships: :person).as_json(include: [:people])

这将返回您的预期结果的房子。在您的包含内,您键入房屋之间的关系->所有权(复数),然后从所有权->人(单数,因为所有权属于)]

© www.soinside.com 2019 - 2024. All rights reserved.