我有一个Location
型号,可以有许多子区块,或者一个父位置.
假设位置-A是父位置,位置-B和位置-C作为子块.但是位置-B也有一个子块位置-D.
如何获取父位置-A的所有子块,包括位置-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
目前,我是这样获取它们的:
def all_sub_location_ids
[id] + sub_locations.map(&:all_sub_location_ids).flatten
end
但我需要一个有效的方法.因为它投出了stack level too deep
编辑:我最终在子区块上使用了.reload
,并保持现有方法不变.这样就行得通了.