Nội dung chính
Cài đặt jQuery và jQuery-ui
Copy
Copy
config/webpack/environment.js
1
yarn add popper.js jquery jquery-ui
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/