通过递归has\u-many关系创建has\u-many关系

cu6pst1q  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(215)

情况:

class Company < ActiveRecord::Base
  has_many :groups #<-- recursive sub-groups
  has_many :profiles, through: :groups #<-- This only returns the :profiles of the first groups layer
end

class Group < ActiveRecord::Base
  belongs_to :company, optional: true
  belongs_to :group, optional: true
  validate :company_xor_group
  has_many :groups
  has_many :profiles
end

class Profile < ActiveRecord::Base
  belongs_to :group
end

示例数据:

company = Company.new
  group = Group.new.profiles.build(name: 'A')
  sub_group = Group.new.profiles.build([{name: 'B'},{name: 'C'}])
  group.groups << sub_group
  company.groups << group

因此,一家公司有一个组,其中包含一个配置文件和一个子组,其中包含两个配置文件。
所以我想得到公司的所有资料。目前, has_many :profiles, through: :groups 关系,仅返回第一个子组的配置文件:

company.profiles.length # 1

我正在寻找一个返回activerecord associationproxy的解决方案。我尝试了以下方法:


# Company Model

def all_profiles
  groups.map(&:all_profiles)
end

# Group Model

def all_profiles
  profiles + groups.map(&:all_profiles)
end

但这将返回一个数组,而不是 AssociationProxy .

qni6mghb

qni6mghb1#

正如@spickermann所回应的,递归表的一个巨大帮助就是嵌套集。
@arieljuod给出了我的问题“如何让它返回activerecord associationproxy?”的答案:


# Company Model

def all_profiles
  Profile.where(group_id: groups.map(&:all_groups).flatten.map(&:id))
end

# Group Model

def all_groups
  [self].push(groups.map(&:all_groups)).flatten.compact
end

在我的解决方案中,这仍然非常有效,因为递归组是预加载的。所以 all_groups 方法不会触发任何新查询。

相关问题