views:

38

answers:

1

I'm looking for a best practice solution to be able to keep using redirect :back after a successful destroy action, as many items can be deleted from a variety of listings.

Unfortunately that strategy fails for the one case when the delete is initiated from the item view itself.

What approach do you recommend for this situation?

A: 

You need to consider what behaviour you'd like if an item is deleted from its own view page..

I'd suggest one of two options:

Keeping your redirect :back, and implementing some kind of second redirection if the requested resource no longer exists - i.e. /products/10 redirects to /products

@product = Product.find_by_id(params[:id]) # although I admit I'm not sure
redirect_to products_path unless @product  # about this

Or change the redirect if the particular path matches the destroyed one

@product.destroy # you might need to save the path before you destroy the object..
redirect_to :back and return unless request.referrer == product_path(@product)
redirect_to products_path

I don't think there's a set-in-stone standard for this kind of scenario, but may I stand corrected.

Jeriko
I like your 2nd option as it avoids another redirect. Thanks.
Andreas
Correction: redirect_to :back and return unless request.referer == product_path(@product)
Andreas
Fixed, thanks :)
Jeriko
It's referer (not referrer) and I think product_url (instead of product_path).
Andreas