所以,在过去的几个小时里,我一直在用头撞墙,试图得到这个。另外,当我知道下面的东西的名称时,我会更改问题的名称。
第一个问题,这个叫什么? #<Comment:0x007fda3aaeb7c8>
这是从数据库返回的。
其次,我正在尝试返回(呈现 json)包含子评论的评论。
像这样:
[
{
id: 1,
title:'title',
body:'body'
},
{
"#< Comment:0x007fda3b3517f0>": {},
"#< Comment:0x007fda3b3517f0>": {},
}
]
如何返回这些评论的值?当我将它们放入控制台时,它会显示它们的属性和值,如下所示:
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 对评论进行排序。
任何建议,尤其是第一个问题,我们将不胜感激。
编辑: 返回评论的 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
最佳答案
该输出是输出的默认字符串表示形式 - 类名加上底层对象的原始指针值。您尝试做的一些事情(例如转换为 json)尝试将其输入转换为字符串(通过 to_s
方法)
看起来您将注释作为散列中的键,如果输出应该是 json,这就没有意义了——JSON 中的键必须是字符串。
关于ruby-on-rails - Rails - 返回嵌套属性的所有值,而不仅仅是 'pointer',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39051437/