我在rails中使用ancestry gem来嵌套一些注释,我想要的是能够获得所有注释然后将它们全部嵌套。当我将@comments = post.comments.arrange_serializable
放入我的评论控制器索引操作并得到以下结果时,我怎么能得到以下结果:
{
"comments":[
{
"id":3,
"comment":"284723nbrkdgfiy2r84ygwbdjhfg8426trgfewuhjf",
"author":"asdasdasdas",
"post_id":268,
"ancestry":null,
"created_at":"2014-06-17T19:23:04.667Z",
"updated_at":"2014-06-17T19:23:04.667Z",
"children":[
{
"id":4,
"comment":"284723nbrkdgfiy2r84ygwbdjhfg8426trgfewuhjf",
"author":"asdasdasdas",
"post_id":268,
"ancestry":"3",
"created_at":"2014-06-17T19:24:02.408Z",
"updated_at":"2014-06-17T19:24:02.408Z",
"children":[
]
}
]
},
{
"id":5,
"comment":"97ryhewfkhbdasifyt834rygewbfj,dhsg834",
"author":"asdasdasd",
"post_id":268,
"ancestry":"4",
"created_at":"2014-06-17T20:30:04.887Z",
"updated_at":"2014-06-17T20:38:16.060Z",
"children":[
]
}
]
}
很明显,id: 5
的评论应该位于children
的数组中,该数组位于评论id: 4
中, IS 嵌套在评论{ {1}}。
有人可以告诉我为什么id: 3
没有“多巢”的评论?或者如果有另一个功能来执行此操作。
答案 0 :(得分:1)
<强>结构强>
您的arrange_serializable
似乎正在运作 - 我认为问题在于您如何嵌套评论
我们发现(带我们年龄),如果你想使用&#34;嵌套&#34;类别,你需要使用这样的slash
:
因此,如果您正在尝试深度嵌套&#34;,您需要确保包括到根对象的整个路径。共同的逻辑建议&#34;继承&#34;嵌套对象也允许它们嵌套 - 不是这样。
-
<强>修正强>
对于id
5
,您应该将ancestry
列设为此值:
$ rails c
$ comment = Comment.find 5
$ comment.update(ancestry: "3/4")
-
<强>部分强>
如果您想在视图中显示嵌套的类别数组,我们使用以下代码:
#app/views/elements/_category.html.erb
<!-- Categories -->
<ol class="categories">
<% collection.arrange.each do |category, sub_item| %>
<li>
<!-- Category -->
<%= category.title %>
<!-- Children -->
<% if category.has_children? %>
<%= render partial: "category", locals: { collection: category.children } %>
<% end %>
</li>
<% end %>
</ol>
#app/views/application/index.html.erb
<%= render partial: "category", locals: { collection: Category.all } %>