こんにちは。たなか(@tanaka_ricecake)です。
Ruby on RailsでWebアプリケーションサービスの開発をしています。
先日開発中に以下のようなエラーメッセージに遭遇しました。
You tried to define a scope named "new" on the model "Title", but Active Record already defined a class method with the same name.
もくじ
Active Record already defined a class method with the same name
ターミナルに以下のような内容のエラーメッセージが表示されました。
ArgumentError (You tried to define a scope named "new" on the model "Title", but Active Record already defined a class method with the same name.):
なるほど。Titleモデルに記述した「new」というscopeは既に定義されているとのことで、利用ができないみたいです。
Active Record already defined a class method with the same name 解決方法
Scope名を変更する!
言われた通り、scopeで利用しようとしたnewというメソッドをリネームしてやります。
今回は「new_title」という名前に変更しました。
scope :new_title, -> {
Title.joins(:title_label).where(name: 'NEW')
}
scope名を修正したことでActive Record already defined a class method with the same name
のエラーは解消されました!よかったー!
Active Record already defined a class method with the same name はenumも同様
今回はモデルのscope名で発生した事象でしたが、同様のエラーはenumなどの設定でも起きやすいです。
「new」や「all」など、active_recordに既にあるメソッド名と被ると、定義することができずActive Record already defined a class method with the same name
になります。
Active Record already defined a class method with the same name まとめ
ということで今回はActive Record already defined a class method with the same name
エラーの解消方法についてご紹介しました。
【Rails】よく使う検索内容はscopeにまとめると良いですよ【初学者必見】でscopeの利便性についてご紹介していましたが、メソッド名を安直にしすぎると今回のようなエラーに遭遇することもあるんですね。
短いですが、今回はここまで。