SystemStackError: stack level too deep

Background

While working on a Rails application, I recently encountered a perplexing error message that left me scratching my head. The error message in question was a “SystemStackError” with the message “stack level too deep,” and it occurred in the context of a controller action. Initially, I was unsure about the root cause of this error and why it suddenly appeared.

Expected Culprit

SystemStackError in DashboardsController#show
stack level too deep

Extracted source (around line #11):

    else
      > @questions = current_organization.questions.in_dashboard
        @subjects  = current_organization.subjects.in_dashboard
    end
  end

Rails.root: /Users/john/projects/lgprofile

Application Trace | Framework Trace | Full Trace
app/controllers/dashboards_controller.rb:11:in `show'

At first glance, the code on line #11 in the dashboards_controller.rb file seemed perfectly fine to me. It hadn’t been modified in quite some time, so it didn’t appear to be the cause of the error. I also checked the associations in the model, thinking that perhaps something had changed there and was triggering the error. To my surprise, I found no recent changes in the model association code.

However, as I continued to investigate, I noticed some new lines of code in the model file:

Real Culprit

  +  scope :parents, -> { where(question_id: nil) }
  +

Upon closer inspection, it became clear that these lines were responsible for the error. When I commented out this code, the application started running smoothly once again.

Reason Behind This Error

Now, let’s delve into the reason behind this puzzling error and why those seemingly innocent lines of code caused such a headache.