Rails - in what order depends => destroy?

In this example:

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 

Will this be the destruction order when I call server.destroy ?

  • Server#clients , as well as Client before/after_destroy callbacks
  • Server will be destroyed
  • and then Server after_destroy callback
+4
source share
1 answer

You can very easily test. I took your code and executed callbacks with a simple puts call. Then it ran script/console and had access to the ActiveRecord console:

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

Set up the base environment:

 >> 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>] 

And here is the gist:

 >> 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"> 

So it looks like you were dead on target. :)

PS

  • There is a small syntax error in the after_destroy server model.
  • I assume that from step 1 you really meant before_destroy , as shown in your example.
+6
source

Source: https://habr.com/ru/post/1300164/


All Articles