【问题标题】:How to use a custom helper via the "helper" method in Rails 3?如何通过 Rails 3 中的“帮助器”方法使用自定义帮助器?
【发布时间】:2011-09-06 22:59:39
【问题描述】:

我正在尝试创建一个这样的自定义助手:

# 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>

我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 helper


    【解决方案1】:

    在控制器中将助手作为 mixin 包含进来怎么样...

    class MyController < ApplicationController
      include MyHelper
    
      def index
        puts foo
      end
    end
    

    【讨论】:

      【解决方案2】:

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

      class MyController < ApplicationController
        helper_method :my_helper
      
        private 
        def my_helper
          "text"
        end
      end
      

      【讨论】:

      • 我没有意识到你可以做到这一点......虽然在某些方面我希望我现在不知道:P(它很有可能被过度使用)
      • 啊哈 :) 权力越大,责任越大;)
      【解决方案3】:

      从视图访问助手,而不是控制器。因此,如果您尝试将以下内容放入索引模板中,它应该可以工作:

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

      如果您确实想从控制器访问某些内容,那么您应该使用 include 语法而不是 helper,但在这种情况下不要将其命名为 helper 模块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-02
        • 1970-01-01
        • 1970-01-01
        • 2010-09-16
        • 1970-01-01
        • 1970-01-01
        • 2011-04-29
        • 1970-01-01
        相关资源
        最近更新 更多