Rails ActiveRecord:after_update 和 after_touch 之间的区别?

Rails ActiveRecord: difference between after_update and after_touch?

提问人:Jon Lawton 提问时间:8/5/2022 更新时间:8/11/2022 访问量:233

问:

我不认为它们是彼此的同义词,而是在功能上相似。

  1. 甚至在触摸时触发,还是只忽略触摸?after_update
  2. 是触发更新,还是只触发触摸?after_touch
ruby-on-rails 回调 rails-activerecord

评论


答:

2赞 smathy 8/11/2022 #1
[11] pry(main)> Foo.after_touch -> { Rails.logger.debug "after_touch called" }
=> [Foo(id: integer, name: string, age: date, created_at: datetime, updated_at: datetime)]
[12] pry(main)> Foo.after_update -> { Rails.logger.debug "after_update called" }
=> [Foo(id: integer, name: string, age: date, created_at: datetime, updated_at: datetime)]
[13] pry(main)> Foo.last.update name: "New name"
  Foo Load (0.1ms)  SELECT "foos".* FROM "foos" ORDER BY "foos"."id" DESC LIMIT ?  [["LIMIT", 1]]
  TRANSACTION (0.0ms)  begin transaction
  Foo Update (0.2ms)  UPDATE "foos" SET "name" = ?, "updated_at" = ? WHERE "foos"."id" = ?  [["name", "New name"], ["updated_at", "2022-08-10 21:10:37.296537"], ["id", 2]]
after_update called
  TRANSACTION (0.8ms)  commit transaction
=> true
[14] pry(main)> Foo.last.touch
  Foo Load (0.1ms)  SELECT "foos".* FROM "foos" ORDER BY "foos"."id" DESC LIMIT ?  [["LIMIT", 1]]
  TRANSACTION (0.0ms)  begin transaction
  Foo Update (0.2ms)  UPDATE "foos" SET "updated_at" = ? WHERE "foos"."id" = ?  [["updated_at", "2022-08-10 21:08:09.188057"], ["id", 2]]
after_touch called
  TRANSACTION (0.7ms)  commit transaction
=> true

评论

0赞 Jon Lawton 8/11/2022
非常简洁的答案。我知道从技术上讲,我没有把它放在问题中,但如果你也想编辑、追加和输出,那将是一个奖励。savesave touch: false