欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

使用gem 'jquery-ui-rails' 列表添加拖拽排序.

参考: https://www.jianshu.com/p/d9911c234107

 

1.先增加一个排序的字段,叫做 position

 b/db/migrate/20170426070834_add_column_position_to_goods.rb
class AddColumnPositionToGoods < ActiveRecord::Migration
  def change
    add_column :goods, :position, :integer
  end
end

2.添加gem 

 gem 'jquery-ui-rails', '4.0.5'

3.b/app/assets/javascripts/application.js.erb 引用js:

//= require jquery.ui.all

4.app/controllers/goods_controller.rb 中添加action    (我们的列表叫 goods 表)

  @goods = @goods.order(:position).page(params[:page])

  def sort
    if params[:goods].present?
      JSON.parse(params[:goods]).each_with_index do |x, index|
        idx = x["id"]
        position = index + 1
        good = Good.find(idx)
        good.update_attribute("position", position)
      end
    end
    render nothing: true
  end

5.app/views/goods/index.html.erb 页面添加:

  
     <% if @goods.present? %>
         <% @goods.each do |good| %>
           
             <%= good.name %>
             <%= good.good_second_category.name rescue '' %>
           
         <% end %>
     <% end %>
  
<script>
    $('#good_table').sortable({
        opacity: 0.6,
        revert: true,
        cursor: 'move',
        update: function() {
            neworder = new Array();
            $(this).children().each(function() {
                id = $(this).attr("data-id");
                neworder.push({
                    id: id
                });
            });

            $.ajax({
                url: "/goods/sort",
                type: "POST",
                data: {
                    goods: JSON.stringify(neworder)
                }
            });

            console.log(neworder);
        }
    }).disableSelection();
</script>

6.config/routes.rb 添加路由:

   resources :goods do
     collection do
       post :set_hot
       post :sort
     end
   end

返回列表