After reading this (the @thomasfedb answer), I though this would work:
@categories = Category.joins(:category_users).where("category_users.user_id = ? AND category_users.interested_learning IS TRUE", current_user.id)
@search = Resource.joins(:categories).where(category_id: @categories.subtree_ids).search_filter(params[:search_filter]).paginate(:per_page => 20, :page => params[:page]).search(params[:q])
But instead, I receive this error
undefined method `subtree_ids' for #<ActiveRecord::Relation:0x007fce832b1070>
I also tried @Rahul answer from here
Without the Ancestry descendants, it is working like this
@search = Resource.joins(:category_users).where("category_users.user_id = ? AND category_users.interested_learning IS TRUE", current_user.id).search_filter(params[:search_filter]).paginate(:per_page => 20, :page => params[:page]).search(params[:q])
Although I want to do the Ransack search after finding the descendants, the error also appears without Ransack. For this reason, I haven't included it in the title. Without Ransack, it would be like this:
@categories = Category.joins(:category_users).where("category_users.user_id = ? AND category_users.interested_learning IS TRUE", current_user.id)
@resources = Resource.joins(:categories).where(category_id: @categories.subtree_ids)
I would appreciate any advices on this could work
@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]