gpt4 book ai didi

ruby-on-rails - 为什么 ActiveRecord after_initialize 和 after_find 回调文档提到 block 级变量?

转载 作者:太空宇宙 更新时间:2023-11-03 16:58:58 30 4
gpt4 key购买 nike

我定义了一个 after_initialize和一个 after_find在我的 User 中回调这样的模型:

请假设我的 User有一个名为 email 的属性也是。

class User < ApplicationRecord
after_initialize do |user|
puts "You have initialized an object! Email: #{email}"
end

after_find do |user|
puts "You have found an object! Email: #{email}"
end
end

按照我在 Rails Guides 中找到的文档.

这按预期工作。 IE。当我调用 User.newUser.first我看到输出按预期打印:

2.3.3 :001 > User.new(email: 'foo@gmail.com')
You have initialized an object! Email: foo@gmail.com
=> #<User id: nil, email: "foo@gmail.com", password_digest: nil,
created_at: nil, updated_at: nil, email_confirmation_token: nil,
terms_of_service: false, country_id: nil>

2.3.3 :002 > User.first
User Load (0.6ms) SELECT "users".* FROM "users" ORDER BY "users"."id"
ASC LIMIT $1 [["LIMIT", 1]]
You have found an object! Email: mary@gmail.com
You have initialized an object! Email: mary@gmail.com
=> #<User id: 10, email: "mary@gmail.com", password_digest:
"$...", created_at: "2017-06-10 06:46:05", updated_at: "2017-07-02
09:52:46", email_confirmation_token: "yStnErkVCFC9mYNHKFNYdA",
terms_of_service: true, country_id: nil>

我的问题是为什么回调文档提到 block 局部变量 user 的存在?从我上面的经历可以看出,user未使用局部变量,但我仍然可以访问 User实例实例化和/或找到。

最佳答案

这些没有 record item 的回调(在你的例子中是一个 user 实例)将没有多大意义(如果有的话) - 除了像你的情况这样的测试目的,当你您只是通过调用 puts 确认自己已找到记录,通常,在实际用例中,您可能需要在应用中使用此对象之前读取/修改它。

因此,当您定义回调时,ActiveRecord 将它们存储在内部。 ActiveRecord 假定您将需要此实例,并且在调用您的 block do ... end 时,它会使用找到的记录 (user) 来完成。理论上(我没有检查 ActiveRecord 代码库中的实际实现)可能看起来像:

 record = find_record
if after_find_callback
after_find_callback.call(record)
end

关于ruby-on-rails - 为什么 ActiveRecord after_initialize 和 after_find 回调文档提到 block 级变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45254380/

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