ActiveSupport中未定义的方法

时间:2016-01-16 22:59:11

标签: ruby-on-rails activesupport 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声明中。它是否与我的User类扩展ActiveRecord::Base有关?或者可能与我从类方法(即some_methods())调用self.create_user()这一事实有关?

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

1 个答案:

答案 0 :(得分: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

模型/ user.rb:

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

rails console:

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