0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rails】Model名とControllerのModule名が重複してNoMethodErrorが発生した時の対応

Posted at

備忘を兼ねて

Moduleとモデル名が重複するとNoMethodErrorになる

ファイル構成

app
├── controllers
│   └──user
│        └── hoges_controller.rb
└── models
    └── users.rb
hoges_controller.rb
module User
    class HogesController < User::ApplicationController
        def index
            User.where(id: ids)
        end
        ## その他メソッド省略
    end
end
エラー内容
NoMethodError in User::HogesController#index
undefined method `where' for User::Module

エラーの原因

モデル名とコントローラー側で定義したモデュール名が重複しており、Userを呼び出すとModule側が優先されてしまう。

対策

モデルを呼び出したい時は::を頭につけるだけ。

hoges_controller.rb
            ::User.where(id: ids)
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?