我有一个简单的通用模型rails,如下所示:
class Thing < ApplicationRecord
attribute :foo, :integer
include AConcern
end它包含一个基本的关注点,看起来就像这个…
module AConcern
extend ActiveSupport::Concern
end该模型还具有一个名为:foo的属性,使用下面的属性api:
https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html
属性与关注点相关,所以每次我想要使用关注点时,我都必须在每个模型中定义属性,然后包含关注点。
如果我将属性解密放在关注点中,如下所示:
module AConcern
extend ActiveSupport::Concern
attribute :foo, :integer
end我得到以下错误:
undefined method `attribute' for AConcern:Module如何在关注点中使用属性定义,以便在包含关注点之前不必在每个模型中声明它?谢谢
发布于 2019-04-09 21:05:30
你可以使用ActiveSupport::Concern包含的钩子来处理这个问题,例如
module AConcern
extend ActiveSupport::Concern
included do
attribute :foo, :integer
end
end 然后
class Thing < ApplicationRecord
include AConcern
end您现在遇到的问题是,在您的Module上下文中调用了attribute,但是该模块没有访问该方法的权限(因此是NoMethodError)。
included挂钩在您调用include时运行,并且该挂钩在包含Object (在本例中为Thing )的上下文中运行。Thing确实有attribute方法,因此一切都按预期工作。
来自ActiveSupport::Concern的included代码块本质上与(纯ruby)相同
module AConcern
def self.included(base)
base.class_eval { attribute :foo, :integer }
end
endhttps://stackoverflow.com/questions/55593533
复制相似问题