gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中组织复杂的回调?

转载 作者:行者123 更新时间:2023-12-04 09:56:55 25 4
gpt4 key购买 nike

我有一个 Rails 应用程序,它经常使用回调......所以我有很多函数在多个模型中被调用 :after_create 和 :after_commit 。

我想知道我现在的做法是否是最好的。

基本上我有以下场景:

Class Parent < ActiveRecord::Base

has_many :children


after_create :first_function
after_commit :last_function

def first_function
if !self.processed?
self.children.create(:name => "Richard The Lion Heart")
self.processed = true
self.save!
end
end

def last_function
if self.processed?
if !self.processing?
self.process
self.save!
self.processing = true
self.save!
end
end
end

end

所以你可以看到整个事情取决于一些奇怪的双重 bool 检查,因为否则每次更新模型时都会调用 second_function 并且它可以由函数本身更新,因此该函数被重复调用。

总的来说,它导致我必须为每个要触发的回调引入一个新的 bool 检查。它有效,但我不认为它优雅。我错过了什么?

最佳答案

你应该能够重写那个代码——像这样?当然,您的真实代码可能有一些额外的复杂性——另外:此代码未经测试。

Class Parent < ActiveRecord::Base
has_many :children

# only called when a new record is created
after_create :first_function

# only called for updates, not new records, should still be inside the current transaction
after_update :last_function

private
def first_function
self.children.create(:name => "Richard The Lion Heart")
# don't call save in here, already in a transaction
end

def last_function
self.process
# don't call save in here, already in a transaction
end

def process
# doing stuff ....
self.children[0].update_attribute(:name, "Beowulf")
end
end

http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html

That’s a total of twelve callbacks, which gives you immense power to react and prepare for each state in the Active Record life cycle. The sequence for calling Base#save for an existing record is similar, except that each _create callback is replaced by the corresponding _update callback.



用法
p = Parent.new(:foo => "bar")
p.save
p.children[0].name
# => "Richard The Lion Heart"

p.update_attributes(:baz => "fud")
p.children[0].name
# => Beowulf

来自 rails 控制台的 ActiveRecord 回调(使用 awesome_print ap)
> ap ActiveRecord::Callbacks::CALLBACKS
[
[ 0] :after_initialize,
[ 1] :after_find,
[ 2] :after_touch,
[ 3] :before_validation,
[ 4] :after_validation,
[ 5] :before_save,
[ 6] :around_save,
[ 7] :after_save,
[ 8] :before_create,
[ 9] :around_create,
[10] :after_create,
[11] :before_update,
[12] :around_update,
[13] :after_update,
[14] :before_destroy,
[15] :around_destroy,
[16] :after_destroy,
[17] :after_commit,
[18] :after_rollback
]

关于ruby-on-rails - 如何在 Rails 中组织复杂的回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11532911/

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