I am using the awesome_nested_set gem and am trying to get all the descendants of a has_many relationship. A User has many tasks shared to them and each task has many children. Ho do I get a list of a Users tasks_shared_to and all their children (note the children are not shared to the user individually)?
User model:
has_many :tasks_shared_to, through: :user_task_shares, source: :task
Task Model:
acts_as_nested_set
belongs_to :created_by, :class_name => 'User', :foreign_key => 'created_by_id'
belongs_to :parent, :class_name => 'Task', :foreign_key => 'parent_id'
I know this would be easy to do with a loop through each tasks_shared_to and then calling self_and_descendants
but I would like to be able to do this without doing a separate SQL call within each loop.
I ended up ditching the awesome_nested_set gem and followed through this excellent blog:
http://hashrocket.com/blog/posts/recursive-sql-in-activerecord
I then modified the class methods to accept an array of objects, extracted to a module and added a few methods like so:
and then included in my task model:
Ten I can call with any number of methods eg:
This gets the job done in only 1 query!