我有一个ActiveRecord类MyClass
,其中包含数据库中的一些字段,其中包含以下问题:
module Wrapper
extend ActiveSupport::Concern
included do
puts self #=> MyClass
puts self.columns #=> Array of ActiveRecord::ConnectionAdapters::PostgreSQLColumn
end
end
我第一次访问此类(例如MyClass.first
)时,我得到了预期的输出(如上所述)。
如果我第二次尝试拨打MyClass.first
,则不会显示任何输出,如果我运行MyClass.columns
而没有包含我关注的问题:
output error: #<NoMethodError: undefined method 'name' for #<Object:0x007fd1f20d0ef0>>
你能帮我理解这里发生了什么吗?
有问题的方法是ActiveRecord::Attributes::ClassMethods#columns。
我理解包含块中的代码是scoped to the context of the class这是有意义的(使这个问题更加神秘)。
如果可以的话,也会很棒:
我正在运行Rails 4.2.0和Ruby 2.2.0