I am trying to fetch self-referential data from Rails. I have a model called Task with the following code:
class Task < ActiveRecord::Base
has_many :tasks
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_tasks, through: :relationships, source: :followed
scope :orphans, :conditions => "id NOT IN (SELECT DISTINCT followed_id FROM relationships)"
In my controller I would like to get all of the tasks with their children (subtasks) and grandchildren.
So far I have been doing this:
@tasks = Task.orphans.to_json(:include => { :followed_tasks => {
:include => :followed_tasks}})
That is probably not the most efficient way but it is one that I could come up with that works. Now if I want to have more levels of nesting this code quickly becomes hard to maintain. How could I improve my code to be able to specify a variable like maxLevelsNum = 4 and then have my query somehow fetch tasks with their subtasks four levels deep?
It’s been a while since the question was asked, but, you can find below a possible answer (maxLevelsNum needs to be greater or equal to 1):