我在回形针中见过GEM has_attached_file :avatar
.
我如何才能为模型创建这样的方法?
我的目标是,每当我定义像custom_method :attribute
这样的属性时,我就可以在活动记录回调上运行一些活动操作,如保存和删除.
我在回形针中见过GEM has_attached_file :avatar
.
我如何才能为模型创建这样的方法?
我的目标是,每当我定义像custom_method :attribute
这样的属性时,我就可以在活动记录回调上运行一些活动操作,如保存和删除.
它只是一个类方法.
def self.custom_method(attribute)
before_save do
do_stuff_with(attribute)
end
define_method "do_stuff_with_#{attribute}" do
do_stuff_with(attribute)
end
do_other_stuff
end
您可以将它添加到您的ApplicationRecord
中,以便在任何地方都可以使用它,或者将它添加到Concern
/Mixin
/Module
中,当您想要使用它时可以将其包括在内.