'Reload Instance Variable Hot Wire
I have a product counter in my index.html.erb as follows:
<p class='text-sm'><%= @products.count %> Products</p>
@products is instantiated in the controller method as follows:
def index
@products = Product.all
end
In the controller I have a delete action, when it is successful it redirects back to the index page:
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
However my @products.count does not update. I am using Rails 7 with Hotwire.
Having a look at my logs, the following happens on redirect:
Started GET "/products" for 127.0.0.1 at 2021-12-22 18:57:58 +0000
Processing by ProductsController#index as TURBO_STREAM
Do instance variables reload automatically on redirect, and if not, how can I make it reload?
Solution 1:[1]
Its possible there was an issue with the objects destruction. Like an association that will break if you delete it. That's why you should use the destroy method as a conditional to make sure it only redirects if destroy was successful
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yungindigo |
