LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】同一名のmodule内でクラスを呼び出す方法

Last updated at Posted at 2022-08-15

状況

一見問題なさそうだが
User.hoge_methodUserモデルではなく、Parameters::User:ModuleUserが呼ばれてしまっているためエラーが起きている。
moduleとクラス名が同一のため起きていると考えられる。

class User
   def hoge_method
      puts 'hogeメソッドを実行'
   end
end


module Parameters
  module User
    class ProfileParameter
        def fuga_method
            User.hoge_method
        end
      end
    end
  end
end
NoMethodError:
undefined method `hoge_method' for Parameters::User:Module

解決法

クラス名の前に::をつける。
ちなみに外部の定数を呼び出すときにも同じ::を使用する。

module Parameters
  module User
    class ProfileParameter
        def fuga_method
          ::User.hoge_method
        end
      end
    end
  end
end

Laravelだったら

moduleは使ったことがないが、もしLaravelで同一名のクラスなどを定義するとき

use App\Models\User as ModelUser;

のように別名を定義できるので便利。

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