Jorge Cuevas Jorge Cuevas - 3 months ago 23
Ruby Question

SystemStackError (stack level too deep) when deleting a record

I'm getting a Stack Overflow error when deleting a record:


SystemStackError (stack level too deep):
app/controllers/orders_controller.rb:18:in `destroy'


I found another System Stack Error related to ruby, but I did not completly get how to fix it since my problem is slightly different.

It is here: Ruby, stack level too deep (SystemStackError)

This is the method, and the second line is causing the error:

def destroy
@order = Order.find(params[:id]).destroy
flash.now[:success] = true
flash.now[:success_title] = "¬°Orden eliminada!"
flash.now[:succes_message] = "La orden #{@order.id} fue eliminada."
respond_to do |format|
format.html {redirect_to orders_path}
format.js {}
end


What can I change to fix this issue?

Answer

The stack level too deep error occurs when you try to delete a record with relationships that declare dependent: :destroy linking back to each other.

Example:

class Order < ActiveRecord::Base
  has_many :items, dependent: :destroy
end

class Item < ActiveRecord::Base
  belongs_to :order, dependent: :destroy
end

Removing dependent: :destroy from the Item assocation should resolve the circular error/stack level too deep.