Rails 在使用 Turbo 的情况下 link_to 弹出确认窗口

koell · 2022年05月31日 · 最后由 xianyuit 回复于 2022年05月31日 · 353 次阅读

Turbo 一般情况下用 button_to 来弹出确认窗口

<%= button_to "Delete", post, method: :delete, form: { data: { turbo_confirm: "Are you sure?" } } %>

如果需要用 link_to 的话,controller 内需要使用 303 重定向。否则 Turbo 会使用 DELETE method 请求重定向地址。

View:

<%= link_to "Delete", post, data: { turbo_method: :delete, turbo_confirm: "Are you sure?" } %>

Controller:

redirect_to(posts_path, status: :see_other)

谢谢分享。这些细节,包括一些参数,目前 Hotwired 文档里没有描述得很清楚,往往需要找找才能解决问题。混着 Rails ujs,感觉目前还是一个过度阶段。

不错,一般删除方法要加上 status: :see_other 是标配,不过验证弹出还有很多方法:

用 stimulus:

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  showConfirmation(event) {
    if (!confirm(event.params.message)) {
      event.preventDefault();
    }
  }
}

html 里:

{ "data-confirmation-message-param": I18n.t("labels.are_you_sure"), "data-action": "confirmation#showConfirmation" }
需要 登录 后方可回复, 如果你还没有账号请 注册新账号