Rails 6 默认使用了UJS,使<a>元素点击时发起一个非get请求,比如post、put、delete,还可以在执行请求之前触发一个弹窗确认。

而在Rails 7 里,这2项功能,推荐使用Turbo代替。

代码举例:

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

实战:

$ rails new confirm-dialog

$ rails g scaffold posts name:string body:string published:boolean

$ rails db:migrate

打开app/views/posts/show.html.erb,并编辑删除链接的代码

<%= link_to "Destroy this post", post_path(@post), data: {turbo_method: "delete", turbo_confirm: "确认删除吗?"} %>

打开app\controllers\posts_controller.rb,并编辑destroy动作的代码

  # DELETE /posts/1 or /posts/1.json
  def destroy
    @post.destroy

    redirect_to action: :index, status: :see_other
  end

启动服务

$ rails s

浏览器打开 http://127.0.0.1/posts/new,输入名称和内容,点击创建按钮

点击”Destroy this post“,会出现弹窗

点击”确认“按钮,跳转到post列表页 /posts

结束!!

加客服微信:qsiq17,开通VIP下载权限!VIP全站资源免费下载!!!