在Rails中从控制器调用helper方法时的“undefined method”

有谁知道我为什么得到

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

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

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

和我的帮手

 module ApplicationHelper def my_method(string) return string end end 

最后是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创build方法。

编辑 :要清楚,我认为很多的困惑(纠正我,如果我错了)源于helper :all呼吁。 helper :all真的只包括所有的帮手,在视图方面的任何控制器下使用。 在Rails的早期版本中,helpers的命名空间决定了哪些控制器的视图可以使用助手。

我希望这有帮助。

view_context是你的朋友, http: //apidock.com/rails/AbstractController/Rendering/view_context

如果你想分享控制器和视图之间的方法,你有更多的select:

在Application_controller.rb文件中包含ApplicationHelper,如下所示:

 class ApplicationController < ActionController::Base protect_from_forgery include ApplicationHelper end 

这样,在application_helper.rb文件中定义的所有方法都将在控制器中可用。

您也可以在个别控制器中包含个人帮手。

也许我错了,但不是帮助只是意见? 通常,如果您需要控制器中的函数,则将其放入ApplicationController中,因为每个函数都有可用的子类。

正如在这篇文章中说的那样:

  • 在Rails 2中使用@templatevariables。
  • 在Rails 3中,使用控制器方法view_context

助手是为视图,但添加一行代码,以包含该助手文件在ApplicationController.rb可以照顾你的问题。 在你的情况下,在ApplicationController.rb中插入以下行:

 include ApplicationHelper 

尝试在你的帮助模块中追加module_function(*instance_methods) ,之后你可以直接调用模块本身的那些方法。

据我所知, helper :all使助手在视图中可用…

我有同样的问题…

你可以绕过它,把这个逻辑放到模型中,或者专门为它做一个类。 控制器可以访问模型,不像那些讨厌的辅助方法。

这是我的“rag.rb”模型

 class Rag < ActiveRecord::Base belongs_to :report def miaow() cat = "catattack" end end 

这是我的“rags_controller.rb”控制器的一部分

 def update @rag = Rag.find(params[:id]) puts @rag.miaow() ... 

我点击“更新”后,终于在terminal上发生了攻击。

给定一个实例,可以调用模型中的方法。 用一些代码replacecatattack。 (这是迄今为止最好的)

:帮手都只能打开助手的意见。

这显示了如何创build一个类并称之为。 http://railscasts.com/episodes/101-refactoring-out-helper-object?autoplay=true

试试这个直接从你的控制器view_context.helper_name访问帮助函数

尽pipe在控制器中调用helper并不是一个好习惯,因为helpers是为了在视图中使用而在控制器中使用helper的最好方法是在application_controller中创build一个helper方法,并将它们调用到控制器,
但即使需要在控制器中调用帮助程序
那么只需在控制器中包含帮助器

 class ControllerName < ApplicationController include HelperName ...callback statements.. 

并直接调用帮助器方法到控制器

  module OffersHelper def generate_qr_code(text) require 'barby' require 'barby/barcode' require 'barby/barcode/qr_code' require 'barby/outputter/png_outputter' barcode = Barby::QrCode.new(text, level: :q, size: 5) base64_output = Base64.encode64(barcode.to_png({ xdim: 5 })) "data:image/png;base64,#{base64_output}" end 

调节器

 class ControllerName < ApplicationController include OffersHelper def new generate_qr_code('Example Text') end end 

希望这可以帮助 !

Interesting Posts