2

我越来越: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

我究竟做错了什么?我怎样才能避免这个问题?

4

2 回答 2

1

include is generally used to include code at the instance level, where extend is for the class level. In this case, you'll want to look to have User extend ApplicationHelper. I haven't tested this, but it might be that simple.

RailsTips has a great write-up on include vs. extend - I highly recommend it.

于 2013-11-13T19:25:08.213 回答
0

它不是 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
于 2013-11-13T19:39:11.127 回答