ruby-on-rails - 为什么redirect_to在创建操作中不起作用?

标签 ruby-on-rails ruby-on-rails-6

这里是 Rails 初学者, 不知何故,我找不到在创建记录后重定向用户的方法。

我有这个 Controller :

  def create
    @product = Product.new(product_params)

    respond_to do |format|
      if @product.save
        format.html { redirect_to @product, notice: 'Product successfully created' }
      else
        format.html { render :new, notice: 'Error' }
      end
    end
  end

  def product_params
    params.require(:product).permit(:name, :description, :price, :quantity, :status, :image)
  end

我尝试了一些变体,例如redirect_toproduct_path(@product)或删除format block ,但没有任何效果。用于提交值的模型和表单似乎有效(验证已通过,记录已保存)。

日志:

Parameters: {"..."}
  User Load (0.2ms)  SELECT ....
  ↳ app/controllers/application_controller.rb:15:in 'admin?'
   (0.1ms)  BEGIN
  ↳ app/controllers/products_controller.rb:24:in 'block in create'
  Product Exists? (0.4ms)  SELECT 1 ...
  ↳ app/controllers/products_controller.rb:24:in 'block in create'
  Product Create (3.3ms)  INSERT INTO ...
  ↳ app/controllers/products_controller.rb:24:in 'block in create'
   (55.3ms)  COMMIT
  ↳ app/controllers/products_controller.rb:24:in 'block in create'
Redirected to http://localhost:3000/products/4137
Completed 200 OK in 65ms (ActiveRecord: 59.3ms | Allocations: 4974)

有什么东西阻止了重定向(更改页面后我仍然有 notice 消息),但 Controller 、表单、模型和日志对我来说看起来没问题。 有谁知道这里可能负责什么?任何帮助将不胜感激!

最佳答案

如果您在 Rails 6 中使用 form_with 帮助程序,那么默认情况下它们是 XHR 表单,并且它们需要一个 js 格式的模板。要使它们响应 html 格式,请添加 local: true 选项。

<%= form_with(model: @product, local: true) do |f| %> 

来自 Rails 指南,

:local - By default form submits are remote and unobtrusive XHRs. Disable remote submits with local: true.

更多信息 - form_with options

希望有帮助!

关于ruby-on-rails - 为什么redirect_to在创建操作中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60617547/

相关文章:

ruby-on-rails - “此锁文件必须使用Bundler 2或更高版本。”即使安装了Bundler 2.0.2

ruby-on-rails - Rails 错误地将重定向响应发送为状态 200

ruby-on-rails - rails : distance_of_time_NOT_in_words

javascript - 在 Rails 上将复选框默认设置为 true

ruby-on-rails - ruby 包安装需要 : no such files to load error

ruby-on-rails - 获取最后插入值的快捷方式。 rails

ruby-on-rails - PG::UndefinedTable: 错误: 关系 "active_storage_blobs"不存在

ruby-on-rails - 如何在 Rails 6 中使用 cocoon gem

ruby-on-rails - 查询参数和 assert_generates/assert_routing - 我错过了什么?

ruby-on-rails-6 - ActiveStorage::Blob 的未知属性 'service_name'