从Rails中的控制器调用helper方法时的"未定义方法"

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文件中定义的所有方法都将在控制器中可用.

您还可以在各个控制器中包含单独的帮助程序.


ste*_*tex 7

也许我错了,但不仅仅是观点的助手?通常,如果您需要控制器中的函数,则将其放入ApplicationController中,因为它的子类中有可用的每个函数.


che*_*ech 6

至于说通过gamecreature这篇文章:

  • 在Rails 2中使用@template变量.
  • 在Rails 3中使用控制器方法 view_context