控制器中的助手 - Rails 3
我从 Rails 2.x 迁移到 3.x。现在当调用控制器方法时抛出
nil:NilClass 的未定义方法“my_helper_method”
MyController.rb
class MyController < ApplicationController
def foo
@template.my_helper_method
end
end
MyControllerHelper.rb
class MyControllerHelper
def my_helper_method
puts "Hello"
end
end
ApplicationController
class ApplicationController < ActionController::Base
helper :all
end
如何让它工作?
I migrated from rails 2.x to 3.x. Now when calling a controller method throws
undefined method `my_helper_method' for nil:NilClass
MyController.rb
class MyController < ApplicationController
def foo
@template.my_helper_method
end
end
MyControllerHelper.rb
class MyControllerHelper
def my_helper_method
puts "Hello"
end
end
ApplicationController
class ApplicationController < ActionController::Base
helper :all
end
How to get this working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这实际上在另一篇SO帖子中得到了回答:Rails 3:@template变量内部控制器为零
本质上,您可以将
@template
替换为view_context
This is actually answered in another SO post: Rails 3: @template variable inside controllers is nil
Essentially, you can replace
@template
withview_context
@template
是一个对象,在您的情况下是nil
。如果此对象中没有方法 (my_helper_method
),则无法调用它(尤其是当它为 nil 时)。在帮助器中定义的方法像常规方法一样被调用。但不是在控制器中,它们是在视图中调用的。您的
helper :all
只是使所有助手都可用于视图。因此,在您看来:
my_helper_method :arg1, :arg2
如果您的对象需要一个方法 (
@template
),则需要为您的对象提供此方法。示例:
助手的作用:
混合助手(将视图助手与视图和模型混合时,请注意代码中是否会出现混乱)
@template
is an object, in your casenil
. If this object doesn't has the method (my_helper_method
) in it, you cannot call it (especially not if it is nil).Methods defined in helpers are called like regular methods. But not in controllers, they are called in views. Your
helper :all
just makes all helpers available to the views.So, in your view:
my_helper_method :arg1, :arg2
IF you need a method for your object (
@template
), you need to give your object this method.Example:
What helpers do:
Mixing in a helper (be aware of having a mess in your code when mixing view helpers with views and models)