Rails和Mutli嵌套中的祖先gem
我在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
注释假设位于注释id: 4
中的子数组中,这些注释id: 4
嵌套在id: 3
注释下。
有人可以告诉我为什么arrange_serializable
不会“多巢”评论? 或者如果有另一个function来执行此操作。
结构体
您的arrange_serializable
似乎正在运作 – 我认为问题在于您如何嵌套评论
我们发现(花了我们年龄),如果你想使用“嵌套”类别,你需要使用这样的slash
:
因此,如果您尝试“深度嵌套”,则需要确保将整个路径包含在根对象中。 通用逻辑建议从嵌套对象“inheritance”也允许它们嵌套 – 不是这样。
–
固定
对于你的id
5
,你应该将ancestry
列ancestry
这个值:
$ rails c $ comment = Comment.find 5 $ comment.update(ancestry: "3/4")
–
局部
如果要在视图中显示嵌套的类别数组,请使用以下代码:
#app/views/elements/_category.html.erb <% collection.arrange.each do |category, sub_item| %> - <%= category.title %> <% if category.has_children? %> <%= render partial: "category", locals: { collection: category.children } %> <% end %>
<% end %>
#app/views/application/index.html.erb <%= render partial: "category", locals: { collection: Category.all } %>