我如何告诉 Rails 从顶级目录自动加载命名空间模型?

How can I tell Rails to autoload namespaced models from a top-level directory?

如何告诉 Rails (5 beta3) 在 app/models 而不是 app/models/namespace 中查找命名空间模型?

我有

module MyApp
  class User < ApplicationRecord
    ...
  end
end

如果我把它放在 app/models/myapp 中,Rails 会找到它。但是,由于我的所有模型都在 MyApp 模块中,我宁愿将它们保留在 app/models.

谢谢

不,您不能告诉 Rails 在自动加载路径(如 (app/models) .当 Rails 看到 MyApp::User(在不在模块定义内的代码中)时,它只会在自动加载路径的目录中查找 my_app/user.rb

很多时候您可以通过不使用限定常量来欺骗 Rails。如果您的控制器在同一个命名空间中,则以下将起作用:

app/controllers/my_app/users_controller.rb

module MyApp
  class UsersController < ApplicationController
    def index
      @users = User.all
    end
  end
end

app/models/user.rb

module MyApp
  class User < ActiveRecord::Base
  end
end

Rails 不知道控制器中引用的 User 是顶级还是 MyApp,因此它会查找 app/models/user.rbapp/models/my_app/user.rb。同样,您可以从其他命名空间模型自动加载 app/models 中的命名空间模型。

但是,一旦您需要从本身不是自身的代码中引用命名空间模型,您就会碰壁(也就是说,您必须手动要求模型 class 文件)在命名空间中,例如在控制台或单元测试中。将控制器放在子目录中但模型不放在子目录中是很愚蠢的。而且您会使查看您的代码的任何人感到困惑。所以最好的办法是遵循 Rails 约定,将命名空间模型放在 app/models.

的子目录中