gpt4 book ai didi

ruby-on-rails - After_save 带参数

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

这是我的模型代码:

after_create :notify_cards_create
after_destroy :notify_cards_destroy
after_update :notify_cards_update

def notify_cards_update
WebsocketRails[:home].trigger 'cards', {type: 'update', card: self.as_json({small: true})}
end

def notify_cards_create
WebsocketRails[:home].trigger 'cards', {type: 'create', card: self.as_json({small: true})}
end

def notify_cards_destroy
WebsocketRails[:home].trigger 'cards', {type: 'destroy', card: self.as_json({small: true})}
end

如您所见,它包含许多重复项!我怎样才能将这段代码缩短为:

after_create :notify_cards_create,   'create'
after_destroy :notify_cards_destroy, 'destroy'
after_update :notify_cards_update, 'update'

谢谢!

最佳答案

我会这样实现:

after_create ->(obj) { notify_cards('create') }
after_destroy ->(obj) { notify_cards('update') }
after_update ->(obj) { notify_cards('destroy') }

protected

def notify_cards(event_type)
WebsocketRails[:home].trigger 'cards', {type: event_type, card: self.as_json({small: true})}
end

lambda 的 obj 参数不是强制性的,但如果您想访问正在创建/更新/删除的对象,则可以使用它

关于ruby-on-rails - After_save 带参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27567389/

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