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...>
我有两个问题:
为什么 some_method
未定义?在我看来,我将它正确地包含在语句 include UserConcern
中。跟我User
class延长ActiveRecord::Base
有关系吗?或者可能与我从 class 方法(即 self.create_user()
)调用 some_methods()
这一事实有关?
为什么 运行 时间错误指的是 #<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
我有一个扩展 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
class延长ActiveRecord::Base
有关系吗?或者可能与我从 class 方法(即self.create_user()
)调用some_methods()
这一事实有关?为什么 运行 时间错误指的是
#<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