从Rails 3控制器调用帮助器方法

问题描述:

是否可以从控制器调用帮助器方法?如果是的话,如何在Rails 3中做到这一点?从Rails 3控制器调用帮助器方法

+6

是的,这是可能的。你可以在这里找到答案: http://*.com/questions/453762/nomethoderror-when-trying-to-invoke-helper-method-from-rails-controller – alexkv 2012-01-18 11:05:21

+0

请标记“view_context.some_helper_method”作为答案谢谢您。 – Vinozio 2014-05-29 19:21:09

view_context.some_helper_method 
+1

这是Rails 3最正确的答案。 – 2014-01-19 11:44:35

您可以在控制器中包含助手模块,也可以将助手定义为控制器方法,并通过helper_method :method_name将其标记为助手。

class FooHelper 
    def bar ... end 
end 

class QuxsController 
    include FooHelper 
end 

class QuxsController 
    private 
    def bar ... end 
    helper_method :bar 
end 

这是工作,如果有人想利用ApplicationHelper方法在其他的控制器或视图中只添加这include ApplicationHelper在下面给出,因为所有的控制器都是从ApplicationController的。

class ApplicationController < ActionController::Base 
    protect_from_forgery  
    include ApplicationHelper 
end