gpt4 book ai didi

ruby-on-rails - 将我在多个模型中使用的自定义回调放在哪里

转载 作者:数据小太阳 更新时间:2023-10-29 07:22:01 24 4
gpt4 key购买 nike

假设我有两个具有相同回调的模型:

class Entry < ActiveRecord::Base
belongs_to :patient
validates :text, presence: true
after_validation :normalizeDate

def normalizeDate
self.created_at = return_DateTime(self.created_at)
end
end

class Post < ActiveRecord::Base
after_validation :normalizeDate

def normalizeDate
self.created_at = return_DateTime(self.created_at)
end
end

共享回调代码放在哪里?谢谢

 def normalizeDate
self.created_at = return_DateTime(self.created_at)
end

最佳答案

Marek 的回答很好,但 Rails 的方式是:

module NormalizeDateModule
extend ActiveSupport::Concern

included do
after_validation :normalize_date
end

def normalize_date
self.created_at = return_DateTime(created_at)
end
end

Doc here .

(你有一个专门的文件夹:models/concerns)

关于ruby-on-rails - 将我在多个模型中使用的自定义回调放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23559708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com