2
0

More than 1 year has passed since last update.

private method `hogehoge' called for のエラーで大混乱したお話

Posted at

概要

最近GASとJavaScriptをお勉強中の @Keichan_15 です:v:

Railsの開発を行う際にとあるエラーに遭遇したのですが、参考記事があまり見当たらず解決に時間が掛かったので、備忘録も兼ねてまとめておこうと思います。
意外と解決方法はシンプルでした…:cry:

伝えたいこと

  • Classの外 でそのメソッド定義していない?
    • def 式がクラス定義の (トップレベル)にあれば private
    • def 式がクラス定義の にあれば public

早速見ていきましょう!

発生しているエラー

2023-03-07 (2).jpg

private method 'hoge' called for ~~ のエラーが出ています。
特にモデル側(今回であれば User )にprivate methodを定義した覚えはないんですが…。:frowning2:

実際のコード

app/models/user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates :name, uniqueness: true, length: {in:2..20}
  validates :introduction, length: {maximum: 50}

  has_many :books, dependent: :destroy
  has_many :book_comments, dependent: :destroy

  ## 以降のコードは割愛 ##

end

def following?(user)
  following_user.include?(user)
end

UserのClass following? を定義している状況です。
つまりここが怪しそう…。

解決方法

app/models/user.rb
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates :name, uniqueness: true, length: {in:2..20}
  validates :introduction, length: {maximum: 50}

  has_many :books, dependent: :destroy
  has_many :book_comments, dependent: :destroy

  ## 以降のコードは割愛 ##

  # Class内にメソッドを移行
  def following?(user)
    following_user.include?(user)
  end

end

Classの following? メソッドを移行しました。

Rubyの リファレンスマニュアル によると、 def式がClassの に定義 されている場合、デフォルトで private に定義されるようです。

デフォルトでは def 式がクラス定義の外(トップレベル)にあれば private、クラス定義の中にあれば public に定義します。

すなわち、Class に定義する場合は public 扱いとなるため、メソッドの呼び出しが可能となってエラーが解消できるということですね。

おわりに

エラー解決って結局のところ、公式ドキュメントを読み込むことで解決することが多い…。
もっと読み込んでいきたいと思った今日この頃でした。
ばいばい。:wave:

2
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
2
0