ActiveSupport 关注中的未定义方法

Undefined method in ActiveSupport concern

我有一个扩展 ActiveRecord::Base 并包含问题的模型:

class User < ActiveRecord::Base
    include UserConcern

    def self.create_user()
        ...
        results = some_method()
    end

end

UserConcern存放在concerns目录下:

module UserConcern
    extend ActiveSupport::Concern

    def some_method()
        ...
    end
end

当我尝试通过调用如下所示的 create_user 方法来创建新用户时,出现了 运行 次错误:

undefined method 'some_method' for #<Class:0x000000...>

我有两个问题:

  1. 为什么 some_method 未定义?在我看来,我将它正确地包含在语句 include UserConcern 中。跟我Userclass延长ActiveRecord::Base有关系吗?或者可能与我从 class 方法(即 self.create_user())调用 some_methods() 这一事实有关?

  2. 为什么 运行 时间错误指的是 #<Class:0x000000...> 而不是 #<User:0x000000...>

试一试

models/concerns/user_concern.rb:

module UserConcern
  extend ActiveSupport::Concern

  def some_instance_method
    'some_instance_method'
  end

  included do
    def self.some_class_method
      'some_class_method'
    end
  end
end

models/user.rb:

class User < ActiveRecord::Base
  include UserConcern
  def self.create_user
    self.some_class_method
  end
end

rails 控制台:

user = User.new
user.some_instance_method
# => "some_instance_method"

User.some_class_method
# => "some_class_method"

User.create_user
# => "some_class_method"

http://api.rubyonrails.org/classes/ActiveSupport/Concern.html