2011-06-02 85 views
2

我试图创建一个自定义帮助这样的:如何通过Rails 3中的“帮手”方法使用自定义助手?

# app/controllers/my_controller.rb 
class MyController < ApplicationController 
    helper :my 
    def index 
    puts foo 
    end 
end 

# app/helpers/my_helper.rb 
module MyHelper 
    def foo 
    "Hello" 
    end 
end 

但是,我得到了以下错误:

undefined local variable or method `foo' for #<MyController:0x20e01d0> 

我缺少什么?

回答

1

帮助者是从视图访问,而不是控制器。所以,如果你试图把你的索引模板中的下列它应该工作:

#my/index.html.erb 
<%= foo %> 

如果你想从控制器访问的东西,那么你应该使用包括语法,而不是帮助,但不要将其命名就像那种情况下的辅助模块一样。

2

通常,我会做相反的事情:我使用控制器方法作为助手。

class MyController < ApplicationController 
    helper_method :my_helper 

    private 
    def my_helper 
    "text" 
    end 
end 
+0

我不知道你能做到这一点......虽然在某些方面,我想我没有现在知道:P(它有很大的潜力被过度使用) – d11wtq 2011-06-02 12:51:42

+0

ahah :)大国有很大的责任;) – apneadiving 2011-06-02 13:04:51

0

如何只包括辅助作为控制器一个mixin ......

class MyController < ApplicationController 
    include MyHelper 

    def index 
    puts foo 
    end 
end 
相关问题