Rails - 返回嵌套属性的所有值,而不仅仅是'指针'

时间:2016-08-20 07:01:02

标签: ruby-on-rails json postgresql nested-attributes

所以,在过去的几个小时里,我一直试着撞到墙上。此外,当我知道下面事物的名称时,我会更改问题的名称。

第一个问题,这叫什么?从数据库返回的#<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

2 个答案:

答案 0 :(得分:1)

该输出是输出的默认字符串表示形式 - 类名加上基础对象的原始指针值。您尝试做的一些事情(例如转换为json)尝试将其输入转换为字符串(通过to_s方法)

看起来你已经将注释作为哈希中的关键字,如果输出应该是json则没有意义 - JSON中的键必须是字符串。

答案 1 :(得分:0)

我的争论的答案是使用.as_json.merge!(children=>[])然后将所有基础评论推送到上面,然后将上述内容推送到评论中

这里有感兴趣的人的回购: https://github.com/jrothrock/comments/