Cha*_*son 41 ruby-on-rails helper helpers applicationcontroller
有谁知道我为什么得到
undefined method `my_method' for #<MyController:0x1043a7410>
Run Code Online (Sandbox Code Playgroud)
当我从ApplicationController子类中调用my_method("string")时?我的控制器看起来像
class MyController < ApplicationController
def show
@value = my_method(params[:string])
end
end
Run Code Online (Sandbox Code Playgroud)
和我的帮手
module ApplicationHelper
def my_method(string)
return string
end
end
Run Code Online (Sandbox Code Playgroud)
最后,ApplicationController
class ApplicationController < ActionController::Base
after_filter :set_content_type
helper :all
helper_method :current_user_session, :current_user
filter_parameter_logging :password
protect_from_forgery # See ActionController::RequestForgeryProtection for details
Run Code Online (Sandbox Code Playgroud)
the*_*eIV 61
您无法从控制器调用帮助程序.ApplicationController如果需要在多个控制器中使用,最好的办法是创建方法.
编辑:要清楚,我认为很多混乱(纠正我,如果我错了)源于这个helper :all电话.helper :all实际上只包括你在视图一侧的任何控制器下使用的所有助手.在早期版本的Rails中,帮助程序的命名空间确定了哪些控制器的视图可以使用帮助程序.
我希望这有帮助.
Vik*_*rón 33
view_context是你的朋友,http: //apidock.com/rails/AbstractController/Rendering/view_context
如果你想在控制器和视图之间共享方法,你还有其他选择:
小智 27
在application_controller.rb文件中包含ApplicationHelper,如下所示:
class ApplicationController < ActionController::Base
protect_from_forgery
include ApplicationHelper
end
Run Code Online (Sandbox Code Playgroud)
这样,application_helper.rb文件中定义的所有方法都将在控制器中可用.
您还可以在各个控制器中包含单独的帮助程序.
| 归档时间: |
|
| 查看次数: |
73669 次 |
| 最近记录: |