1

I'm a newbie to RoR. I want to know what will be the value of object (particularly, instance variable) after destroy in the controller.

For example in the following code, what will be the value of @cart object (instance variable) after invoking the destroy method in the controller.

#app/controllers/carts_controller.rb
def destroy
    @cart.destroy
    respond_to do |format|
      format.html { redirect_to store_url }
      format.json { head :no_content }
    end
end

In addition, I use this @cart object in the view(.html.erb file) to show the list of shopping items. How this @cart object is gonna be happened in this view after destroy.

Thanks.

2 Answers 2

1

That depends in a lot of things.

The short answer is that @cart remains unmodified after the .destroy method call.

The long answer is that can be a bunch ofcallbacks invoked by ActiveRecord or by your own implementation, including the destruction of all the related elements to this cart element. Also the record in the DB has been removed so if you are trying to load a relation, as relations are normally lazy loaded, this relation can be empty if you load it after the destruction of the parent element.

So I recommend to load all the elements that are gonna be used in your view before you destroy the parent one.

0

@cart in your example refers to a particular instance of the Cart model.

The way you've outlined it here, I'm assuming that you're using Rails 4 because the code that actually sets @cart is not in your destroy method

What happens when the DELETE request comes in via HTTP, Rails goes to your data store and returns a copy bound to @cart, when .destroy is called the original item from the data store is destroyed and @cart would then become Nil

@cart used elsewhere should not be affected because each instance related to the data in the data store

Hope this answers your question.

1
  • thanks for answer, but I'm not very sure about @cart would become Nil. Dec 14, 2013 at 13:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.