Rails 7删除操作未触发控制器指定重定向问题
Rails 7.0.4 + Ruby 3.1.2:删除操作无法触发控制器重定向问题
我在使用Rails 7.0.4和Ruby 3.1.2时遇到问题:删除员工后,控制器里定义的重定向到首页的逻辑没有触发,页面没有跳转,但员工确实被删除了。
相关代码
employees_controller.rb
def destroy @employee.destroy respond_to do |format| format.html { redirect_to root_path, notice: "Employee was deleted" } format.turbo_stream { flash.now[:notice] = "Employee was deleted" } end end
_employees.html.erb
<%= turbo_frame_tag "employees" do %> <%= render employees %> <% end %>
_employee.html.erb(删除按钮)
<%= link_to "Delete", employee_path(employee), data: { turbo_method: :delete, turbo_confirm: 'Are you sure?' }, type: "button", class: "inline-block px-6 py-2.5 bg-red-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-red-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out" %>
问题原因
Rails 7默认启用Turbo,点击带有data-turbo-method: :delete的链接时,Turbo会自动发送Turbo Stream格式的请求,而非普通HTML请求。此时控制器会进入format.turbo_stream分支,但这个分支仅设置了flash消息,没有添加页面重定向的逻辑,因此页面不会跳转。
解决方案
有两种可行的处理方式:
方式一:修改Turbo Stream响应,添加重定向
在控制器的format.turbo_stream分支中,使用Turbo支持的redirect_to方法触发页面跳转,同时保留提示消息:
def destroy @employee.destroy respond_to do |format| format.html { redirect_to root_path, notice: "Employee was deleted" } format.turbo_stream do redirect_to root_path, notice: "Employee was deleted" end end end
方式二:强制发送HTML请求
如果不需要Turbo的局部更新能力,可以给删除链接添加data-turbo: false,让请求走控制器的HTML分支:
<%= link_to "Delete", employee_path(employee), data: { turbo_method: :delete, turbo_confirm: 'Are you sure?', turbo: false }, type: "button", class: "inline-block px-6 py-2.5 bg-red-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-red-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg transition duration-150 ease-in-out" %>
注:如果选择方式一,需要确保项目布局中正确渲染了flash消息,Turbo会自动处理提示的显示逻辑。
内容的提问来源于stack exchange,提问作者Christian T
相关产品推荐
相关产品推荐

