Madogiwa Blog

主に技術系の学習メモに使っていきます。

RubyonRails:stack level too deepでハマった話

RailsTutorial中にstack level too deepでハマったのでメモ

エラー画面

f:id:madogiwa0124:20170117000619p:plain

原因

現在ログインしているユーザの取得処理とその呼び出し元のメソッド名が重複していた。

class MicropostsController < ApplicationController
    before_action :logged_in_user,only:[:create,:destroy]
    before_action :current_user,  only: :destroy

    def destroy
        @micropost.destroy
        flash[:success] = "Micropost deleted"
        redirect_to request.referrer || root_url
    end

    private
    def micropost_params
        params.require(:micropost).permit(:content)
    end
   
    def current_user
        # この行のcurrent_userが再起呼び出しになっていた
        # ※本来は、ログイン中のユーザを取得したかった
        @micropost = current_user.microposts.find_by(id: params[:id])
        redirect_to root_url if @micropost.nil?
    end
end

解決方法

呼び出し元のメソッド名を重複しないよう変更した。

class MicropostsController < ApplicationController
    before_action :logged_in_user,only:[:create,:destroy]
    before_action :set_micropost,  only: :destroy

    def destroy
        @micropost.destroy
        flash[:success] = "Micropost deleted"
        redirect_to request.referrer || root_url
    end

    private
    def micropost_params
        params.require(:micropost).permit(:content)
    end

    # メソッド名変更
    def set_micropost 
        @micropost = current_user.microposts.find_by(id: params[:id])
        redirect_to root_url if @micropost.nil?
    end
end

[参考ページ] teratail.com