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

发布一下 0 0


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
Rails7 如何使点击a元素时,发起delete请求?如何使弹窗确认?

$ rails g scaffold posts name:string body:string published:boolean
Rails7 如何使点击a元素时,发起delete请求?如何使弹窗确认?

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

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

<%= link_to "Destroy this post", post_path(@post), data: {turbo_method: "delete", turbo_confirm: "确认删除吗?"} %>
Rails7 如何使点击a元素时,发起delete请求?如何使弹窗确认?

打开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
Rails7 如何使点击a元素时,发起delete请求?如何使弹窗确认?

启动服务

$ rails s


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

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


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



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

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


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


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


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

结束!!

版权声明:内容来源于互联网和用户投稿 如有侵权请联系删除

本文地址:http://0561fc.cn/109995.html