如何高效获取Location模型的所有嵌套子对象?
如何获取层级Location模型的所有子位置(含深层子节点)?
我有一个Location模型,支持层级关联:一个位置可以拥有多个子位置,也可归属一个父位置。例如location-A作为父位置,包含子位置location-B和location-C,而location-B又有子位置location-D。现在需要实现获取父位置location-A的所有子位置(包括深层的location-D)。
模型关联代码
has_many :sub_locations, class_name: "Location", foreign_key: "parent_location_id", inverse_of: :parent_location belongs_to :parent_location, optional: true, class_name: "Location", foreign_key: "parent_location_id", inverse_of: :sub_locations
原实现及问题
我最初尝试用递归方法获取所有子节点ID:
def all_sub_location_ids [id] + sub_locations.map(&:all_sub_location_ids).flatten end
但运行时会抛出stack level too deep错误,需要更可靠的实现方式。
解决方案
最终我通过在子位置集合上调用.reload,保留原有递归逻辑解决了问题,修改后的代码如下:
def all_sub_location_ids [id] + sub_locations.reload.map(&:all_sub_location_ids).flatten end
内容的提问来源于stack exchange,提问作者cnn
相关产品推荐
相关产品推荐

