1

我的 index.html.erb 中有一个产品计数器,如下所示:

<p class='text-sm'><%= @products.count %> Products</p>

@products在控制器方法中实例化如下:

def index
    @products = Product.all
end

在控制器中,我有一个删除操作,当它成功时,它会重定向回索引页面:

def destroy
    @product = Product.find(params[:id])
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url }
      format.json { head :no_content }
    end
  end

但是我@products.count的没有更新。我正在使用带有 Hotwire 的 Rails 7。

查看我的日志,重定向时会发生以下情况:

Started GET "/products" for 127.0.0.1 at 2021-12-22 18:57:58 +0000
Processing by ProductsController#index as TURBO_STREAM

实例变量是否在重定向时自动重新加载,如果没有,我怎样才能让它重新加载?

4

1 回答 1

0

对象销毁可能存在问题。就像删除它会破坏的关联一样。这就是为什么你应该使用destroy方法作为条件来确保它只在destroy成功时重定向

def destroy
  @product = Product.find(params[:id])
  if @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url }
      format.json { head :no_content }
    end
  else
    ... there was an issue destroying
  end
end
于 2022-02-22T16:38:57.270 回答