Search code examples
ruby-on-railsruby-on-rails-3error-handlingdestroy

How to display an error message on a destroy action, since it redirects to index action?


In a model I have:

before_destroy :ensure_not_referenced_by_any_shopping_cart_item

and

def ensure_not_referenced_by_any_shopping_cart_item
  unless shopping_cart_items.empty?
    errors.add(:base, "This item can't be deleted because it is present in a shopping cart")
    false
  end
end

When the item is present in a cart, it is not destroyed (which is good), and I see the error if I log it in the action..

def destroy
  @product = Beverage.find(params[:id])
  @product.destroy

  logger.debug "--- error: #{@product.errors.inspect}"

  respond_to do |format|
    format.html { redirect_to beverages_url }
    format.json { head :ok }
  end
end

..but the instance variable on which the error message was set is abandoned when the redirect_to happens, so the user never sees it.

How should the error message be persisted to the next action so it can be shown in its view?

Thanks!


Solution

  • I would recommend using a flash message to relay the error information.

    respond_to do |format|
      format.html { redirect_to beverages_url, :alert => "An Error Occurred! #{@products.errors[:base].to_s}"
      format.json { head :ok }
    end
    

    Something to that effect. That is how I have handled similar issues in my own apps, but it depends on the detail of information you want to display to the user.