Why can I access helper methods for one controller in the views for a different controller? Is there a way to disable this without hacking/patching Rails?
问题:
回答1:
@George Schreiber's method doesn't work as of Rails 3.1; the code has changed significantly.
However, there's now an even better way to disable this feature in Rails 3.1 (and hopefully later). In your config/application.rb, add this line:
config.action_controller.include_all_helpers = false
This will prevent ApplicationController from loading all of the helpers.
(For anyone who is interested, here's the pull request where the feature was created.)
回答2:
The answer depends on the Rails version.
Rails >= 3.1
Change the include_all_helpers
config to false
in any environment where you want to apply the configuration. If you want the config to apply to all environments, change it in application.rb
.
config.action_controller.include_all_helpers = false
When false, it will skip the inclusion.
Rails < 3.1
Delete the following line from ApplicationController
helper :all
In this way each controller will load its own helpers.
回答3:
In Rails 3, actioncontroller/base.rb
(around line 224):
def self.inherited(klass)
super
klass.helper :all if klass.superclass == ActionController::Base
end
So yes, if you derive your class from ActionController::Base
, all helpers will be included.
To come around this, call clear_helpers
(AbstractClass::Helpers
; included in ActionController::Base
) at the beginning of your controller's code. Source code comment for clear_helpers:
# Clears up all existing helpers in this class, only keeping the helper
# with the same name as this class.
E.g.:
class ApplicationController < ActionController::Base
clear_helpers
...
end
回答4:
Actually in Rails 2, the default functionality of ActionController::Base was to include all helpers.
Changeset 6222 on 02/24/07 20:33:47 (3 years ago) by dhh: Make it a default assumption that you want all helpers, all the time (yeah, yeah)
change:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
end
As of Rails 3 beta 1, that is no longer the case as noted in the CHANGELOG:
- Added that ActionController::Base now does helper :all instead of relying on the default ApplicationController in Rails to do it [DHH]