我有一个扩展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...>
我有两个问题:
为什么some_method
未定义?在我看来,我正确地将其包含在include UserConcern
声明中。它是否与我的User
类扩展ActiveRecord::Base
有关?或者可能与我从类方法(即some_methods()
)调用self.create_user()
这一事实有关?
为什么运行时错误会引用#<Class:0x000000...>
而不是#<User:0x000000...>
?
答案 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