Rails development 模式下自动加载的问题

kingwkb · 2015年09月12日 · 最后由 lolychee 回复于 2015年09月13日 · 1902 次阅读
application_controller.rb
class ApplicationController < ActionController::Base
end

api/application_controller.rb
module Api
  class ApplicationController < ActionController::Base
  end
end

api/users_controller.rb
module Api
  class UsersController < ApplicationController
  end
end

上面代码在 development 模式下,如果先访问过 application_controller 再访问 api/application_controller ,就会出现 api/users_controller 继承了 application_controller ,而不是继承 api/application_controller 的情况,换作启动 rails s 后先访问 api ,就没问题

production 下也没问题

我现在是用 class UsersController < Api::ApplicationController 解决

难道不就应该用 Api::ApplicationController 解决吗? 另外其实建议最好不要给类起一样的名字,否则就会出现你这样的命名冲突的情况。 命名冲突的时候要强制命名路径,比如要严格区分 ::AppCtrler::Api::AppCtrler 而不能就只写一个 AppCtrler。 建议类改名成,比如说, ApiController

#1 楼 @msg7086 是这样的么,如果不是用 module 那肯定类的定义和继承类的写法都是使用全路径,但是包括在 module 里面,不是因该用 ruby 的常量查找方式么,我看很多开源的项目也是这么用的(包括在 module 里面,没有使用全路径)也有 controller 重名的情况,我奇怪他们都不会遇到这个问题么

#2 楼 @kingwkb 这就不太清楚了。我自己没这么干过。

http://edgeguides.rubyonrails.org/configuring.html

你看一下 config/environments/development.rb config.eager_load 应该是 false,这意味着,程序启动时不会加载全部代码,只有执行到时才去寻找加载。

你的代码里,向上搜索 ApplicationController,如果找到了,就不会调用 const_missing,也就不会加载代码了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号