【问题标题】:Reload Instance Variable Hot Wire重新加载实例变量热线
【发布时间】:2022-01-23 23:08:13
【问题描述】:

我的 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

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

【问题讨论】:

  • 您的视图中似乎缺少某些内容。您是否将 p 标签包装在 turbo-frame 标签中?
  • &lt;%= turbo_frame_tag :products do %&gt; &lt;p class='text-sm' id='products-count'&gt;&lt;%= @products.count %&gt; Products&lt;/p&gt; &lt;% end %&gt; 是的,但仍然没有更新。

标签: ruby-on-rails ruby erb hotwire-rails


【解决方案1】:

对象销毁可能存在问题。就像删除它会破坏的关联一样。这就是为什么你应该使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 2022-06-21
    • 1970-01-01
    • 2023-03-15
    • 2017-04-16
    相关资源
    最近更新 更多