Cuộc sống Nhật Bản
Yuto Blog

【Ruby on Rails】Hướng dẫn làm chức năng sort với jquery-ui sortable

HSBC - Mở thẻ tín dụng
Nội dung chính
【Ruby on Rails】Hướng dẫn làm chức năng sort với jquery-ui sortable

Cài đặt jQuery và jQuery-ui

Copy
1
yarn add popper.js jquery jquery-ui
Copy config/webpack/environment.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { environment } = require('@rails/webpacker')

// Add
const webpack = require('webpack')
environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)
// Add

module.exports = environment
Copy app/javascript/packs/application.js
1
2
3
require("jquery")
require("jquery-ui/ui/widgets/sortable")
require("jquery-ui/ui/effects/effect-highlight") // Highlight effect

Giả sử có model là Product, và table products tồn tại column sort dạng integer

Copy app/models/product.rb
1
scope :default_order, -> { order("sort") }
Copy config/routes.rb
1
2
3
4
5
resources :products do
  member do
    patch :sort
  end
end
Copy app/controllers/products_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
def index
  @products = Product.all.default_order
end

def sort
  product = Product.find(params[:id])
  product.update_column(:sort, params[:sort])
  Product.where.not(id: product.id).default_order.each_with_index do |other_product, index|
    sort = index
    sort += 1 if sort >= product.sort
    other_product.update_column(:sort, sort)
  end
end
Copy app/views/products/index.html.slim
1
2
3
4
5
6
7
8
9
10
11
12
table.table.table-striped
  thead
    tr
      th Sort
      th Product name
      th Product code
  tbody.sortable
    - @products.each do |product|
      tr data-url=sort_product_path(product)
        td= product.sort
        td= product.name
        td= product.code
Copy app/javascript/src/sortable.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(document).on("turbolinks:load", function() {
  $(".sortable").sortable({
    update: function(event, ui) {
      $.ajax({
        dataType: "json",
        url: ui.item.data("url"),
        type: "PATCH",
        data: {sort: ui.item.index()}
      });
    },
    // Highlight effect
    stop: function(event, ui) {
      ui.item.children('td').effect('highlight', { color: "#00FF00" }, 500)
    }
  });
});
Copy app/javascript/packs/application.js
1
require("../src/sortable")

Kết quả:
https://yuto-sortable.herokuapp.com/

Updated at 2023-05-09
Nếu bài viết có ích thì các bạn hãy chia sẻ nhé
Rate this article: 5/5 (11 ratings)
You didn't rate yet
Le Minh Thien Toan

Tác giả:Yuto Yasunaga

Xin chào các bạn. Mình là kỹ sư IT đang làm việc ở Nhật Bản. Mình tạo blog này để chia sẻ về cuộc sống và những kinh nghiệm trong quá trình học tập và làm việc.
Hy vọng bài viết này sẽ có ích cho bạn.