【问题标题】:Rails - return all values for nested-attributes, instead of just the 'pointer'Rails - 返回嵌套属性的所有值,而不仅仅是“指针”
【发布时间】: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 对 cme​​ts 进行排序。

非常感谢任何建议,尤其是第一个问题。

编辑: 返回 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


    【解决方案1】:

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

    看起来您将 cmets 作为哈希中的键,如果输出应该是 json,这没有意义 - JSON 中的键必须是字符串。

    【讨论】:

    • 啊,好吧,谷歌搜索我的出路可能是不可能的。这只是我在 Postman 中得到的结果,我不相信它们是实际的字符串,因为 put 确实有效。另外, to_s 确实有效,你知道为什么它们没有完全渲染,只显示它们的指针吗?我更新了问题以显示它是如何呈现的。
    【解决方案2】:

    我的斗争的答案是使用.as_json.merge!(children=&gt;[])然后将所有底层的cmets推到上面,然后将上面的推到评论中

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 2023-03-12
      • 2021-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多