【发布时间】:2016-08-20 07:01:01
【问题描述】:
所以,在过去的几个小时里,我一直在用头撞墙,试图得到这个。另外,当我知道下面事物的名称时,我会更改问题的名称。
第一个问题,这叫什么?从数据库返回的#<Comment:0x007fda3aaeb7c8>。
其次,我正在尝试返回(渲染 json)包含子 cmets 的评论。
类似这样的:
[
{
id: 1,
title:'title',
body:'body'
},
{
"#< Comment:0x007fda3b3517f0>": {},
"#< Comment:0x007fda3b3517f0>": {},
}
]
如何返回这些 cmets 的值?当我将它们放在控制台中时,它会显示它们的属性和值,如下所示:
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>=>{}}
但如果我尝试修改它们——比如 to_a 或 to_json——它只会像这样(因为没有更好的术语)爆炸:
puts comments[0][1].to_a
#<Comment:0x007fda3b1911b8>
{}
#<Comment:0x007fda3b190fd8>
{}
我正在使用 Postgres,并且正在使用closure_tree 的 hash_tree 对 cmets 进行排序。
非常感谢任何建议,尤其是第一个问题。
编辑: 返回 cmets 的 def 索引:
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
【问题讨论】:
标签: ruby-on-rails json postgresql nested-attributes