Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Render as nested JSON #50

Closed
bodrovis opened this issue Mar 25, 2013 · 1 comment
Closed

Render as nested JSON #50

bodrovis opened this issue Mar 25, 2013 · 1 comment

Comments

@bodrovis
Copy link

Hello. Is there any way to render nested resources as JSON? I use closure_tree to implement comments with replies and the method "hash_tree" is very helpful when rendering all this heirarchy in plain HTML. But how can I render the same stuff in JSON, for example like (or anything like this - i just basically need some mechanism to mark which comments are roots, which are children and to which roots they related, in order to render it with AngularJS):

[
  {
    body: "Text of the comment"
    name: "Username"
    comment:
    {
       body: "Nested comment"
       name: "User who posted nested comment",
       comment:
       {
         body: "2 levels nested comment"
         name: "Username"
         comment:
         {
            ....
         }
       }
    }
  }
]

Any help will be much appreciated.

@mceachen
Copy link
Collaborator

In your JSON sample it seems like your "comment" field is the descendants of the node, but there's only one direct child, which is pretty surprising. I'd expect your "comment" field (I'd rename it as "responses") would be an array holding the descendants of that node.

If those expectations were correct, I'd suggest a recursive method in your model that can render the fields you want:

def self.custom_json_hash_tree(tree)
  tree.map { |parent, children| parent.to_custom_hash(children) }
end

def to_custom_hash(children)
  responses = children.map { |ea| self.class.custom_json_hash_tree(ea) }
  {body: self.body, name: self.name, responses: responses}
end

You may get more responses for these sort of general coding questions belong on http://stackoverflow.com, as this isn't specific to this library.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants