gpt4 book ai didi

ruby-on-rails - Rails - 创建回调和嵌套属性后的执行顺序

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

我有一个简单的设置 UserUserProfile模型与用户 has_one :user_profile和用户配置文件 belongs_to :user .

但是我无法理解 Rails 如何定义 after_create 的执行顺序回调和 accepts_nested_attributes_for在我的模型中定义。让我们考虑这两种情况。

案例1:

class User < ActiveRecord::Base
has_one :user_profile
accepts_nested_attributes_for :user_profile
after_create :test_test
end

现在,如果我通过控制台创建一个用户(也带有 user_profile_attributes 哈希), after_create在用户及其用户配置文件创建后触发回调。

案例2:
如果 after_create被放置在顶部,
class User < ActiveRecord::Base
after_create :test_test
has_one :user_profile
accepts_nested_attributes_for :user_profile
end

在创建用户之后但在创建用户配置文件之前触发回调。

这是预期的运作方式吗? Rails 在内部做了什么?执行顺序是否简单地由代码的顺序决定?

我从哪里开始深入研究或调试这个?

最佳答案

模型中声明的顺序可能会影响代码的执行顺序。这是各种奇怪事物的来源。 (例如,当前回调定义和 has_and_belongs_to_many 关联是顺序相关的: https://github.com/rails/rails/pull/8674 )

要调试问题,您需要浏览 rails 源代码。由于您的问题与执行顺序、回调和嵌套属性有关,我将首先阅读:

  • https://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L256
  • https://github.com/rails/rails/blob/master/activerecord/lib/active_record/callbacks.rb#L302
  • https://github.com/rails/rails/blob/master/activemodel/lib/active_model/callbacks.rb#L98

  • 这为您提供了深入挖掘的必要背景。你会注意到 accepts_nested_attributes_for调用 add_autosave_association_callbacks https://github.com/rails/rails/blob/master/activerecord/lib/active_record/autosave_association.rb#L173
    此方法添加一个 after_create回调,据我所知,回调是按定义顺序执行的。

    关于ruby-on-rails - Rails - 创建回调和嵌套属性后的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9631614/

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