“未定义方法"当从Rails中的控制器调用helper方法时 [英] "undefined method" when calling helper method from controller in Rails

查看:152
本文介绍了“未定义方法"当从Rails中的控制器调用helper方法时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道我为什么得到

undefined method `my_method' for #<MyController:0x1043a7410>

当我从ApplicationController子类中调用my_method("string")时?我的控制器看起来像

when I call my_method("string") from within my ApplicationController subclass? My controller looks like

class MyController < ApplicationController
  def show
    @value = my_method(params[:string])
  end
end

和我的助手

module ApplicationHelper
  def my_method(string)
    return string
  end
end

最后是ApplicationController

and finally, 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

推荐答案

您不能从控制器调用助手.最好的选择是,如果需要在多个控制器中使用该方法,请在ApplicationController中创建该方法.

You cannot call helpers from controllers. Your best bet is to create the method in ApplicationController if it needs to be used in multiple controllers.

编辑:需要明确的是,我认为很多困惑(如果我错了,请纠正我)是由helper :all调用引起的. helper :all实际上只是包括了所有可在视图侧的任何控制器下使用的助手.在更早版本的Rails中,助手的命名空间决定了哪些控制器的视图可以使用助手.

EDIT: to be clear, I think a lot of the confusion (correct me if I'm wrong) stems from the helper :all call. helper :all really just includes all of your helpers for use under any controller on the view side. In much earlier versions of Rails, the namespacing of the helpers determined which controllers' views could use the helpers.

我希望这会有所帮助.

I hope this helps.

这篇关于“未定义方法"当从Rails中的控制器调用helper方法时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆