安装 UJS 后,如何在 Rails 7 中删除记录并转到删除页面?

how to delete a record and go to delete page in rails 7 after installing ujs?

提问人:Afaq Khan 提问时间:7/25/2023 最后编辑:Sebastián PalmaAfaq Khan 更新时间:7/26/2023 访问量:61

问:

我正在使用 Rails 7 并安装了 ujs,但是每当我单击删除按钮获取请求调用而不是销毁请求时,我都会转到查看记录页面而不是删除员工页面。这是删除链接的代码:

<%= link_to "Delete", employee_path(employee), method: :delete, class: "btn btn-danger", data: { confirm: "Are You sure to delete this employee" } %>

这是从控制器文件中删除操作的代码:

def destroy
    @employee = Employee.find(params[:id])
    if @employee.destroy
      redirect_to employees_path, notice: "Employee has been deleted"
    end
  end
Ruby-on-Rails Ruby-on-Rails-3 Ruby-on-Rails-7 Rails-UJS

评论

0赞 Sebastián Palma 7/25/2023
你是如何添加rails-ujs的?你的文件是什么样子的?config/importmap.rbapp/javascript/application.js
0赞 Afaq Khan 7/25/2023
@SebastiánPalma这是应用程序的代码.js:从“@rails/ujs”导入 Rails;Rails.start();下面是 impotmap.rb 文件的代码: # 通过运行 ./bin/importmap 固定 npm 包 pin “application”, preload: true pin “@hotwired/turbo-rails”, to: “turbo.min.js”, preload: true pin “@hotwired/stimulus”, to: “stimulus.min.js”, preload: true pin “@hotwired/stimulus-loading”, to: “stimulus-loading.js”, preload: true pin_all_from “app/javascript/controllers”, under: “controllers”
0赞 Sebastián Palma 7/25/2023
“@rails/ujs”是否固定在 importmap.rb 文件中?
0赞 Afaq Khan 7/25/2023
不。如何操作,请让我知道其余的说明@SebastiánPalma
1赞 Sebastián Palma 7/25/2023
尝试在 importmap.rb 文件的末尾添加此行;pin "@rails/ujs", to: "https://ga.jspm.io/npm:@rails/[email protected]/lib/assets/compiled/rails-ujs.js"

答:

1赞 Sebastián Palma 7/25/2023 #1

根据评论,您已经部分安装了 rails-ujs,但仍然缺少 rails-ujs JS 模块的导入。

您可以尝试将 @rails/ujs 模块固定到您的文件中并重新启动服务器:config/importmap.rb

# config/importmap.rb
pin "@rails/ujs", to: "https://ga.jspm.io/npm:@rails/[email protected]/lib/assets/compiled/rails-ujs.js"

有关 的更多信息,请参见 rails/importmap-railspin