On Wednesday, September 9, 2020 at 6:03:53 PM UTC-7, abhijit wrote:
>
> Hi,
>
> I have a table with associations to itself in a parent child hierarchy 
> using parent_id as the foreign key. I can use both the *tree* and the 
> *rcte_tree* Sequel plugins there.
>
> I need to get all the children in a nested format, so I've written a 
> method like this -
>
> class User < Sequel::Model(:users)
>   plugin  :rcte_tree
>
>   def get_all_children
>     below = []
>
>     if self.children.count.zero?
>       below = nil
>     else
>       self.children.each do |child|
>         ret = child.get_all_children
>         below.push ret
>       end
>     end
>
>     self.values.merge({children: below})
>   end
> end
>
> And I'm able to get the response as expected - 
>
> ---
> :id: 1
> :name: AAA
> :parent_id: nil
> :children:
> - :id: 2
>   :name: AA1
>   :parent_id: 1
>   :children:
>   - :id: 3
>     :name: AA2
>     :parent_id: 2
>     :children: nil
>
>
> I was wondering if there is a better way to do this.
>

If you use the rcte_tree plugin, it should be able to retrieve all 
descendants in a single database query.  Here's a more compact version:

class User < Sequel::Model(:users)
  plugin  :rcte_tree

  def get_all_children
    descendants unless children
    values.merge(children: (children.map(&:get_all_children) unless 
children.empty?))
  end
end

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/sequel-talk/3635e483-09bc-438e-b601-554a35d93721o%40googlegroups.com.

Reply via email to