【问题标题】:Ancestry gem in Rails and Mutli NestingRails 和 Mutli Nesting 中的祖先宝石
【发布时间】:2014-06-18 16:18:39
【问题描述】:

我正在使用 rails 中的祖先 gem 来嵌套一些 cmets,我想要的是让您能够获取所有 cmets,然后将它们全部嵌套。当我将:@comments = post.comments.arrange_serializable 放入我的 cmets 控制器索引操作并获得以下结果时,我如何得到以下结果:

{
   "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 嵌套在 id: 3 的评论下。

有人能告诉我为什么arrange_serializable 没有“多巢”cmets 吗?或者如果有其他功能可以做到这一点。

【问题讨论】:

    标签: ruby-on-rails ruby ancestry


    【解决方案1】:

    结构

    您的 arrange_serializable 似乎工作正常 - 我认为问题在于您如何嵌套 cmets

    我们发现(花了我们很多时间)如果你想使用“嵌套”类别,你需要像这样使用slash:

    因此,如果您尝试“深嵌套”,则需要确保包含到根对象的整个路径。常见的逻辑表明从嵌套对象“继承”也将允许它们嵌套 - 不是这样。

    --

    修复

    对于您的 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 } %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      相关资源
      最近更新 更多