0

我有一个模型可以扩展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。这与我的User课程扩展有关ActiveRecord::Base吗?或者可能与我some_methods()从类方法(即self.create_user())调用的事实有关?

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

4

1 回答 1

0

试试看

模型/关注/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

模型/用户.rb:

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

导轨控制台:

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

于 2016-01-17T00:13:25.150 回答