0

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...

Community
  • 1
  • 1
SET001
  • 11,480
  • 6
  • 52
  • 76
  • What's wrong with including a gem? A gem is just wrapping up functionality so that you don't have to look at the dirty bits. If you exclude gems, you're left with rolling your own. –  Mar 08 '13 at 07:20
  • @bdares: As SET said, it's good for learning proposes. I've studied it for a while, how people could be creative. It's necessary to have as much in your brain as possible, so your brain can work with. On the other side it's a waste of time to invent the wheel every time again.. so think about how you would realize it and looking in a solution like ancestry how it was realized there :-) – Robin Mar 08 '13 at 07:37

0 Answers0