closure_tree
closure_tree copied to clipboard
Order children differently
Hi!
I'm using awesome_nested_set today to create nested comments but looking to switch to something else but I have some questions.
Is it possible to have different ordering of nested comments? I want the root comments to be sorted with the newest first, but the rest with the newest last.
Example:
- Comment 2
- Comment 3
- Comment 5
- Comment 6
- Comment 4
- Comment 1
- Comment 7
Today, with awesome_nested_set, I fetch all root comments and then do a separate request for each root to fetch the children.
Is there a more performant way to do it in closure_tree?
Short answer: no.
Have you thought about setting this order at insert time instead (by prepending to head for top level and spending to tail for lower levels) so the select "just works"?
Not sure I understand what you mean.
Do you mean having a separate sort_order
column and use prepend_child
or prepend_sibling
when creating a comment which is nested?
Like this (ish)
class Comment ...
def insert(parent)
if root? || parent.nil?
root.prepend_sibling(self)
else
parent.add_child(self)
Seems nice :)
And then I'd get all my comments correctly with one query?
Btw, is it possible to use pagination with closure_tree?
@mceachen I did it like this
# Comment model
def insert
if root? || parent.nil?
commentable.comments.root.prepend_sibling(self)
else
parent.add_child(self)
end
end
I couldn't just do root.prepend...
because root
is nil.
In my controller
# CommentsController
def create
# Finds the polymorphic `Commentable` (Article, BlogPost ...)
parent = find_parent_model
@comment = parent.comments.build(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.insert
# ....
else
# ....
end
end
end
That should work, right?
Also, does closure_tree work have any support for pagination?
That actually does not work. When I add the first comment commentable.comments.root
is also nil...
Kind of similar: we have a Comments
model as well, and we were hoping to sort by the column we use for acts_as_votable
, or cached_votes_up
. To our dismay, we discovered that closure_tree
was overwriting the sort column with its own sort order. Is it possible to prevent this behavior? Just the behavior where CT writes over the sort order, I mean. I think it would be fine to have CT interpret cached_votes_up
as the sort order, unless it wouldn't be able to handle duplicate sort order values.