【问题标题】:Helpers in controller - Rails 3控制器中的助手 - Rails 3
【发布时间】:2012-01-18 10:21:31
【问题描述】:

我从 rails 2.x 迁移到 3.x。现在调用控制器方法时会抛出

undefined method `my_helper_method' for nil:NilClass

MyController.rb

class MyController < ApplicationController
    def foo
      @template.my_helper_method
    end
end

MyControllerHelper.rb

class MyControllerHelper
    def my_helper_method
      puts "Hello"
    end
end

应用控制器

class ApplicationController < ActionController::Base
   helper :all
end

如何让它工作?

【问题讨论】:

    标签: ruby-on-rails-3 helpers controllers


    【解决方案1】:

    这实际上在另一个 SO 帖子中得到了回答:Rails 3: @template variable inside controllers is nil

    基本上,您可以将@template 替换为view_context

    【讨论】:

      【解决方案2】:

      @template 是一个对象,在你的情况下是 nil。如果此对象中没有方法 (my_helper_method),则不能调用它(尤其是当它为 nil 时)。

      帮助程序中定义的方法被称为常规方法。但不在控制器中,它们在视图中被调用。您的 helper :all 只是使所有助手都可用于视图。

      所以,在你看来:my_helper_method :arg1, :arg2

      如果您需要对象的方法 (@template),则需要为您的对象提供此方法。

      示例:

      class Template < ActiveRecord::Base
      
        def my_helper_method
          # do something on a template instance
        end
      
      end
      
      
      class MyController < ApplicationController
        def foo
          @template = Template.first
          @template.my_helper_method # which actually isn't a helper
        end
      end
      

      助手做什么:

      module MyHelper
        def helper_method_for_template(what)
        end
      end
      
      # in your view
      helper_method_for_template(@template)
      

      混合使用帮助程序(在将视图帮助程序与视图和模型混合时,请注意代码中的混乱)

      class Template < ActiveRecord::Base
        include MyHelper
      
        # Now, there is @template.helper_method_for_template(what) in here. 
        # This can get messy when you are making your helpers available to your
        # views AND use them here. So why not just write the code in here where it belongs
        # and leave helpers to the views? 
      end
      

      【讨论】:

      • 但是您正在迁移到 rails3。我不知道它为什么会起作用,但是助手应该可以帮助您解决问题。如果您想在控制器中包含助手,请在控制器中执行 include MyControllerHelper。但是,这些仍然是“常用”方法,而不是对象的实例方法(例如 @template)。在将辅助方法混合到您的模型/实例库中时,您可以使它们可用于该对象。但这并不真正符合惯例。
      • 你最好使用migrating 而不是patching-everything-so-the-old-things-which-are-not-good-are-still-working。如果您真的想做第二个,请继续使用 rails 2.x。我更新了答案,看看。您想要的是在您的模型中定义这些方法或创建 @template 的任何内容。
      猜你喜欢
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 2012-02-17
      • 2011-09-02
      • 1970-01-01
      • 2016-07-23
      • 2020-11-11
      • 1970-01-01
      相关资源
      最近更新 更多