Rails 3.2.3命名空间控制器被具有相同名称的全局控制器覆盖 [英] Rails 3.2.3 namespaced controllers being overridden by global controllers with same name
问题描述
首先加载全局应用程序控制器时,在该命名空间中加载页面时,不加载命名空间的应用程序控制器。应用程序控制器如下所示:
class ApplicationController< ActionController :: Base
protect_from_forgery
end
命名空间的应用程序控制器看起来像
class Admin :: ApplicationController< ApplicationController
def authenticate_admin!
如果current_admin.nil?
redirect_to new_admin_session_url
结束
结束
私人
def current_admin
@current_admin || = Admin.find(session [ :admin_id])if session [:admin_id]
结束
helper_method:current_admin
结束
当我们使用before_filter authenticate_admin!像这样:
class Admin :: AssetsController< Admin :: ApplicationController
before_filter:authenticate_admin!
end
抛出 Admin :: AssetsController#new中的NoMethodError。仅当我们在命名空间路由之前点击全局路由时,才会发生这种情况。如果重新启动服务器并首先加载了命名空间的路由,则一切正常。
这是因为您也碰巧拥有与名称空间同名的 Admin
模型(一个Class)。
此 Google组线程很好地解释了正在发生的事情。
要修复,我可以将模型重命名为 AdminUser
,或者如果不可能,重命名空间也可以解决此问题。 / p>
When the global application controller is loaded first, the namespaced application controller does not load when loading pages within that namespace. The application controller looks like this:
class ApplicationController < ActionController::Base
protect_from_forgery
end
And the namespaced application controller looks like this:
class Admin::ApplicationController < ApplicationController
def authenticate_admin!
if current_admin.nil?
redirect_to new_admin_session_url
end
end
private
def current_admin
@current_admin ||= Admin.find(session[:admin_id]) if session[:admin_id]
end
helper_method :current_admin
end
When we use the before_filter "authenticate_admin!" like this:
class Admin::AssetsController < Admin::ApplicationController
before_filter :authenticate_admin!
end
A "NoMethodError in Admin::AssetsController#new" is thrown. This only occurs when we hit the global route before the namespaced route. If the server is restarted and the namespaced route is loaded first everything works properly.
This is happening because you also happen to have an Admin
model (a Class) with the same name as your namespace.
This Google group thread provides a good explanation of what exactly is happening.
To fix, I would either rename the model to AdminUser
or if that is not a possibility, renaming the namespace will also fix the issue.
这篇关于Rails 3.2.3命名空间控制器被具有相同名称的全局控制器覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!