我看過很多關于使用 Rails SortableJS 和通過 Ajax 更新物件位置的教程 - 但是,我在 Rails 表單中使用 SortableJS,其中隱藏欄位包含“position”屬性。
移動一個 Sortable 組后,如何更新 Sortable 組的所有元素?
// javascript/controllers/drag_controller.js
connect() {
this.sortable = Sortable.create(this.element, {
animation: 150,
onEnd: this.end.bind(this)
})
}
end(event) {
// Update "position" field of each sortable object
// event.newIndex works as the position of the newly moved item
}
這是嵌套的表單項:
// views/item/_form.html.erb
<%= content_tag :div, class: "nested-fields", data: { new_record: form.object.new_record? } do %>
<div class="form-group">
<%= form.label :name %>
<%= form.text_field :name %>
</div>
<%= form.hidden_field :position %>
<% end %>
除了位置欄位外,該表單目前運行良好。我還使用了acts_as_list,它會自動填充后端的位置,但不適用于使用表單進行編輯的用戶。
uj5u.com熱心網友回復:
根據我的經驗,act_as_list您已經在使用的 gem可以滿足您的需求:自動更新記錄。例如,在 中irb,使用Message模型并銷毀一條記錄:
irb(main):001:0> m = Message.find 11
Message Load (0.8ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
=> #<Message id: 11, content: "e", created_at: "2021-11-30 14:30:37.896535000 0000", updated_at: "2021-11-30 14:41:38.871285000 0000", position: 8>
irb(main):002:0> m.destroy
TRANSACTION (0.4ms) BEGIN
Message Load (0.8ms) SELECT "messages".* FROM "messages" WHERE "messages"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
Message Destroy (2.6ms) DELETE FROM "messages" WHERE "messages"."id" = $1 [["id", 11]]
Message Update All (3.0ms) UPDATE "messages" SET "position" = ("messages"."position" - 1), "updated_at" = '2021-12-01 18:43:34.628679' WHERE (1 = 1) AND ("messages"."position" > 8)
TRANSACTION (5.0ms) COMMIT
您可以看到控制臺中的最后一個操作是Update All,它將通過減少position1 中的屬性來更新記錄。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/371534.html
