So, I've been banging my head against the wall for the past couple of hours trying to get this. Also, I'll change the name of the question when I know the name of the thing below.
First question, what is this called? #<Comment:0x007fda3aaeb7c8>
which is returned from the database.
Secondly, I'm trying to return (render json) a comment that contains child comments.
Something like this:
[
{
id: 1,
title:'title',
body:'body'
},
{
"#< Comment:0x007fda3b3517f0>": {},
"#< Comment:0x007fda3b3517f0>": {},
}
]
How do I return the values of those comments? When I puts them in the console it shows their attributes and values, like so:
puts comments[0][1]
{#<Comment id: 17, body: "Another Reply Test", created_at: "2016-08-20 04:05:16", updated_at: "2016-08-20 04:05:16", parent_id: 13, user_id: 54>=>{}, #<Comment id: 18, body: "Another Reply Test", created_at: "2016-08-20 04:05:16", updated_at: "2016-08-20 04:05:16", parent_id: 13, user_id: 54>=>{}}
but if I try to modify them at all - like to_a or to_json - it just blows up (for a lack of a better term) like such:
puts comments[0][1].to_a
#<Comment:0x007fda3b1911b8>
{}
#<Comment:0x007fda3b190fd8>
{}
I'm using Postgres, and I'm using closure_tree's hash_tree to sort the comments.
Any advice would be very much appreciated, especially with the first question.
EDIT: The def index that returns the comments:
def index
if request.headers["type"] == 'music'
comments = Comment.where("song_id = ?", request.headers["id"]).hash_tree.to_a
comments.each do |comment|
puts comment[1] #shows all attributes and values
puts comment[1].to_a #blows up
puts comment[1].to_s #works
end
end
if comments
render json: {status:200, success:true, comments:comments}
else
render json: {status:404, success:false}
end
end
The answer to my strugle was to use .as_json.merge!(children=>[])
then push all underlying comments into the above, then push the above into the comment
Here's the repo for anyone interested: https://github.com/jrothrock/comments/