在Rails中使用closure_tree gem的nestedSortable

时间:2017-11-13 10:34:24

标签: ruby-on-rails ajax jquery-ui-sortable nested-sortable

一位客户的网络团队要求我提供一个快速的解决方案来拖放他们的管理仪表板上的产品类别。 这是我的解决方案,无需大量代码即可快速完美地工作。

这是closure_tree gem,使模型充当树数据结构中的节点: https://github.com/ClosureTree/closure_tree

这里是JS部分的nestedSortable

以下是我的观点:

<ul class="sort" data-url="<%= sort_admin_catalog_categories_path %>">
<% categories.each do |c| %>
    <%= content_tag_for :li, c do %>
        <ul>
            <%= c.name.upcase %>
            <% if c.child? then %>
                <% c.children.each do |c1| %>
                <%= content_tag_for :li, c1 do %>
                    <ul>
                        <strong><%= c1.name %></strong>
                            <% if c1.child? then %>
                                <% c1.children.each do |c2| %>
                                    <%= content_tag_for :li, c2 do %>
                                    <%= c2.name %>
                                    <% end %>
                                <% end %>
                            <% end %>
                        <% end %>
                    </ul>
                <% end %>
            <% end %>
        </ul>
    <% end %>
<% end %>

JS:

$(document).ready(function() { 
    $('.sort').nestedSortable({
        items: 'li',
        update: function(e, ui) {
        Rails.ajax({
          url: $(this).data("url"),
          type: "PATCH",
          data: $(this).nestedSortable('serialize'),
        });
        }
    });
});

路线:

  resources :categories do
    collection do
      patch :sort
    end
  end

控制器:

  def sort
    params[:category].each_with_index do |id, index|  
        Category.where(id: id).update_all({sort_order: index+1})
    end
    head :ok
  end

请注意,自Rails 5.1起,您应该使用params[:category].to_unsafe_h.each_with_index或为强参数构建相对方法

最后是nestedSortable选项:

    options: {
        disableParentChange: false,
        doNotClear: false,
        expandOnHover: 700,
        isAllowed: function() { return true; },
        isTree: true,
        listType: "ul",
        maxLevels: 0, //infinite
        protectRoot: false,
        rootID: null,
        rtl: false,
        startCollapsed: false,
        tabSize: 20,

如果可以提供帮助。

N.B。 :如果有人想要贡献,我还没有解决N + 1的交易我真的很感激。

0 个答案:

没有答案