Rails - 以什么顺序依赖=>毁灭跟随?

时间:2010-02-03 11:11:34

标签: ruby-on-rails callback

给出这个例子:

class Server < ActiveRecord::Base
  has_many :clients,:dependent => :destroy 
  after_destroy: delete_server_directory
end

class Client < ActiveRecord::Base
  belongs_to :server

  before_destroy :copy_some_important_stuff_from_the_server_directory_before_its_too_late
end

当我拨打server.destroy时,这会是破坏的顺序吗?

  1. Server#clients以及Client的{​​{1}}回调
  2. before/after_destroy将被销毁
  3. 后跟Server的{​​{1}}回拨

1 个答案:

答案 0 :(得分:5)

你可以很容易地测试。我接受了您的代码,并通过简单调用puts来实现回调。然后启动script/console并让ActiveRecord登录到控制台:

>> ActiveRecord::Base.logger = Logger.new(STDOUT)
=> #<Logger:0x0000000308d2f0 ...>

设置一些基本环境:

>> a = Client.create :name => 'Client 1'
  Client Create (0.4ms)   INSERT INTO "clients" ("name", "server_id") VALUES('Client 1', NULL)
=> #<Client id: 1, name: "Client 1", server_id: nil>
>> b = Client.create :name => 'Client 2'
  Client Create (0.5ms)   INSERT INTO "clients" ("name", "server_id") VALUES('Client 2', NULL)
=> #<Client id: 2, name: "Client 2", server_id: nil>
>> server = Server.create :name => 'The Server'
  Server Create (0.3ms)   INSERT INTO "servers" ("name") VALUES('The Server')
=> #<Server id: 1, name: "The Server">
>> server.clients = [a, b]
  Client Load (0.4ms)   SELECT * FROM "clients" WHERE ("clients".server_id = 1) 
  Client Update (0.4ms)   UPDATE "clients" SET "server_id" = 1 WHERE "id" = 1
  Client Update (0.2ms)   UPDATE "clients" SET "server_id" = 1 WHERE "id" = 2
=> [#<Client id: 1, name: "Client 1", server_id: 1>, #<Client id: 2, name: "Client 2", server_id: 1>]

以下是它的要点:

>> server.destroy
>>> copy_some_important_stuff_from_the_server_directory_before_its_too_late called!
  Client Destroy (0.5ms)   DELETE FROM "clients" WHERE "id" = 1
>>> copy_some_important_stuff_from_the_server_directory_before_its_too_late called!
  Client Destroy (0.2ms)   DELETE FROM "clients" WHERE "id" = 2
  Server Destroy (0.2ms)   DELETE FROM "servers" WHERE "id" = 1
>>> delete_server_directory called!
=> #<Server id: 1, name: "The Server">

所以看起来你已经死了。 :)

P.S。

  • 服务器型号after_destroy中存在一个小的语法错误。
  • 我假设步骤1你的意思是before_destroy,如你的例子所示。