LoginSignup
0
0

More than 3 years have passed since last update.

`derive_class_name': stack level too deep (SystemStackError) にハマった

Posted at

stack level too deep エラーの解決について

今回上記エラーによりrails s およびrail c(というか多分全railsコマンド)ができなくなり、その解決方法を備忘録的に記載しておきたい。

症状

console
rails  s

とすると

console
=> Booting Puma
=> Rails 5.2.0 application starting in development 
=> Run `rails server -h` for more startup options
Exiting
Traceback (most recent call last):
        11639: from bin/rails:4:in `<main>'
        11638: from bin/rails:4:in `require'
        11637: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/railties-5.2.0/lib/rails/commands.rb:18:in `<top (required)>'
        11636: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/railties-5.2.0/lib/rails/command.rb:46:in `invoke'
        11635: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/railties-5.2.0/lib/rails/command/base.rb:65:in `perform'
        11634: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        11633: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        11632: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
         ... 11627 levels...
            4: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.0/lib/active_record/reflection.rb:991:in `derive_class_name'
            3: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.0/lib/active_record/reflection.rb:790:in `source_reflection'
            2: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.0/lib/active_record/reflection.rb:769:in `klass'
            1: from /home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.0/lib/active_record/reflection.rb:162:in `class_name'
/home/ec2-user/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.0/lib/active_record/reflection.rb:991:in `derive_class_name': stack level too deep (SystemStackError)

となった。

原因

開発中のアプリにテーブルを3つ追加したタイミングで発生したため、どのテーブル(モデル)に問題があったのかを調べるため、1つずつSchemaに記述していき、洗い出した。(ちなみにridgepole gem使用環境下である)

その後、testsテーブルを該当テーブルと同一内容で作成していき、どのタイミングでエラーが起こるようになるか調べた。

するとtest.rb(modelファイル)に該当テーブルと同じアソシエーション記述をしたタイミングでrails sができなくなったため、アソシエーション記述に問題があると判明。

よく見ると以下のように記述されていた。

test.rb
#hogesは中間テーブル名
has_many: hoges, through: :hoges

中間テーブル経由で中間テーブルとN:Nの関係を記述していたことが判明。

下の記事の回答でもあるが、再帰の問題でエラーを起こしていたっぽい(ケースは異なるが)。
https://teratail.com/questions/56653

解決策

コードを以下のように修正。

hoge.rb
#fugasはアソシエーション持ちたいテーブル
has_many: fugas, through: :hoges

すると問題なくrails sできるように復活。
再帰の問題についてはもっと詳しく学ぶ必要性がありそう。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0