【问题标题】:Calling helper method from Class method: "undefined method"从类方法调用辅助方法:“未定义的方法”
【发布时间】:2013-11-13 18:25:25
【问题描述】:

我收到:undefined method 'important_method' for #<Class:0xbee7b80>

当我打电话时:User.some_class_method

与:

# models/user.rb
class User < ActiveRecord::Base

  include ApplicationHelper

  def self.some_class_method
    important_method()
  end

end


# helpers/application_helper.rb
module ApplicationHelper

  def important_method()
    [...]
  end

end

我做错了什么?如何避免这个问题?

【问题讨论】:

    标签: ruby-on-rails-3 model helpermethods


    【解决方案1】:

    include 一般用于包含实例级别的代码,其中extend 用于类级别。在这种情况下,您需要查看 User extend ApplicationHelper。我还没有测试过,但它可能就这么简单。

    RailsTips 在includeextend 上有a great write-up - 我强烈推荐它。

    【讨论】:

    【解决方案2】:

    它不是 DRY,但它有效 - 将 application_helper.rb 更改为:

    # helpers/application_helper.rb
    module ApplicationHelper
    
      # define it and make it available as class method
      extend ActiveSupport::Concern
      module ClassMethods
        def important_method()
          [...]
        end
      end
    
      # define it and make it available as intended originally (i.e. in views)
      def important_method()
        [...]
      end
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 2011-11-19
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      • 2019-06-05
      相关资源
      最近更新 更多