@categories.subtree_ids
will not work because subtree_ids
is an instance method, whereas you're calling on the ActiveRecord::Relation
. Try this instead:
@categories.map(&:subtree_ids).flatten.uniq
This might not be particularly performant, but ancestry stores and parses a column similar to "10/1/3" to manage hierarchy. The above will likely trigger an N+1 query. Another option would be to parse the columns yourself. I'm not sure if ancestry provides a better way to do this, but it's fairly simple:
arr = @categories.pluck(:ancestry)
#> ["10/1", "5/6/1", "2", nil, nil]
arr.compact
#> ["10/1", "5/6/1", "2"]
arr.map { |ids| ids.split('/') }
#> [["10","1"],["5","6","1"],["2"]]
arr.flatten
#> ["10","1","5","6","1","2"]
arr.uniq
#> ["10","1","5","6","2"]
arr.map(&:to_i)
#> [10,1,5,6,2]
Put it all together (I'd suggest multi-line within a method):
@categories.pluck(:ancestry).compact.map { |ids| ids.split('/') }.flatten.uniq.map(&:to_i)
#> [10,1,5,6,2]