Back

使table可以排序 ( sort table in rails )

发布时间: 2014-10-22 07:38:00

TODO: 把它做成一个gem 

 1. 要有这段js:

  this.make_table_sortable = function(table_css_selector) {
    var base_index, entity_class, this_table;
    this_table = $(table_css_selector);
    base_index = this_table.attr('base_index') || 0;
    entity_class = this_table.attr('entity_class');
    return this_table.sortable({
      axis: 'y',
      dropOnEmpty: false,
      cursor: 'crosshair',
      items: 'tbody tr',
      opacity: 0.4,
      scroll: true,
      update: function() {
        return $.ajax({
          type: 'put',
          data: "" + (this_table.sortable('serialize')) + "&entity_class=" + entity_class + "&base_index=" + base_index,
          dataType: 'json',
          beforeSend: function(xhr) {
            return xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
          },
          complete: function(request) {
            return $().toastmessage('showSuccessToast', '排序成功');
          },
          url: "/commons/sort"
        });
      }
    });
  };

in your controller

+# -*- encoding : utf-8 -*-
+class CommonsController < ApplicationController
+
+  # PUT
+  def sort
+    params.permit :entity_class, :base_index, :ids, :position
+    entity_class = params[:entity_class]
+    # 基础偏移量。一般是0. 如果要兼容现有数据,就设置个比现有数据的position还小的初始值
+    base_index = params[:base_index].to_i || 0
+    params[:ids].each_with_index do |id, index|
+      entity_class.constantize.find(id).update_attribute(:position, base_index + index)
+    end
+    render json: 'success'
+  end
+end

in your table:

<table class='table table-hover table-striped sortable' entity_class='Item'>
   <tbody>
     <% @items.each do |item| %>
      <tr id='ids_<%= item.id %>'>
   </tbody>
</table>

in your config.routes:

+  resources "commons", :only => [] do
+    collection do
+      put :sort
+    end
+  end

好玩的是,这个朋友也写了一个文章,不过它的好复杂。我看不懂哈哈。 refer to : http://benw.me/posts/sortable-bootstrap-tables/

Back