Rails7 如何使点击a元素时,发起delete请求?如何使弹窗确认?

Rails7 如何使点击a元素时,发起delete请求?如何使弹窗确认?

首页休闲益智点击工程师更新时间:2024-07-30

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

结束!!

查看全文
大家还看了
也许喜欢
更多游戏

Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved