Rails helper方法在不应该工作的地方工作?

时间:2013-07-16 13:21:04

标签: ruby-on-rails ruby ruby-on-rails-4

在我的helper/posts_helper.rb文件中,我正在定义一个像这样的方法:

module PostsHelper
    def testing(test)
        "Yep its a #{test}"
    end
end

我认为这个测试助手只能在我的帖子视图中使用。但它适用于我的所有视图,甚至是我的应用程序的其他资源的视图。我不会把它放在application_helper.rb中。怎么会发生?

这是我的application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
end

2 个答案:

答案 0 :(得分:3)

Rails只会加载特定控制器的帮助程序,这是一种常见的误解。默认情况下,Rails将加载所有帮助程序。您需要在application.rb中设置此行:

config.action_controller.include_all_helpers = false

这只会加载你期望的帮助器(控制器的一个,以及它的继承链中的任何东西,比如ApplicationHelper等)。

答案 1 :(得分:0)

在某处检查helper :all,例如您的应用程序控制器。