在 Rails 中实现拖拽排序功能

首先,如果你使用了 webpack,那么你可以在 package.json 中添加:

"jquery-ui": "^1.12.1"

如果没有使用 webpack,那么在 Gemfile 文件中添加:

gem 'jquery-ui-rails'

然后,需要在 application.js 中引入:

import 'jquery-ui/ui/widgets/sortable'

或者

//= require jquery-ui/widgets/sortable

在 view 层,找到你列表的上一个 div,添加如下代码:

.questions-list-body#sortable data-url=upd_position_questions_path

data-url 是你后台进行更新顺序的 api,然后创建 js 文件,代码如下:

$(document).on('turbolinks:load', function () {
 // 排序
  $('#sortable').sortable({
    handle: '.td-sortable',
    stop: function () {
      $.ajax({
        type: 'POST',
        url: $(this).data('url'),
        data: $('#sortable').sortable('serialize'),
      })
    },
  })
})

然后打开页面你会看到已经生成如下 html 页面:

然后我们在写好的 api 接口里面添加:

params[:questions].each_with_index do |q_id, index|
      question = current_team.questions.find(q_id)
      question.update(position: index)
end

然后就可以拖拽排序了。
PS: 有分页暂无法正确排序

猜你喜欢

转载自www.cnblogs.com/Mr-RanX/p/12810231.html