I have a table with nested comments and they have comment_id
field to point to parent comment. I put has_many :comments, :class_name => "Comment"
in comment's model and so i have a tree. The question is how with all power of Rails and ActiveRecord i can get whole comments tree from database and respond with it in json format? I know about ancestry
but i want to find solution without any side gems. I want to learn best ways in Rails for manipulation tree-like structures because this task will appear again and again in my further practice.
UPDATE:
I found some related question here and used answer from it. I define method in model
def self.get_tree(comments)
comments.map { |comment|
{:responses => get_tree(comment.comments), :user => comment.user, :text => comment.text}
}
end
and then just call it to get whole tree (with some conditions)
render :json => Comment.get_tree(Comment
.where('announce_id = ?', params[:id])
.where('comment_id is NULL'))
With this implementation i clearly see now that there no need in side gems for this task. But also in current implementation i should list all comment's properties inside map. Are there any way to just extend existing object with {:responses => get_tree(comment.comments), :user => comment.user}
? I
found << for arrays and .update for hashes but then i ended up with that i have no idea whatcomment
inside map block is. Either it array or hash or object...