dependent 可以設定當物件刪除時,也會順便刪除它的 has_many 物件: class Event < ActiveRecord::Base has_many :attendees, :dependent => :destroy end :dependent 可以有三種不同的刪除方式,分別是: ? :destroy 會執行 attendee 的 destroy 回呼 ? :delete 不會執行 attendee 的 destroy 回呼 ? :nullify 這是預設值,不會幫忙刪除 attendee 要不要執行 attendee 的刪除回呼效率相差不少,如果需要的話,必須一筆筆把 attendee 讀取出來變成 attendee 物件,然後呼叫它的 destroy。如果用:delete 的話,只需要一 個 SQL 語句就可以刪除全部 attendee。 delete destroy destroy是先查出来再删除 2.2.4 :017 > Credit.first.destroy Credit Load (0.5ms) SELECT "credits".* FROM "credits" ORDER BY "credits"."id" ASC LIMIT 1 (0.3ms) begin transaction SQL (0.5ms) DELETE FROM "credits" WHERE "credits"."id" = ? [["id", 2]] (63.3ms) commit transa 2.2.4 :006 > Credit.destroy_all Credit Load (0.6ms) SELECT "credits".* FROM "credits" (0.1ms) begin transaction SQL (0.4ms) DELETE FROM "credits" WHERE "credits"."id" = ? [["id", 7]] (59.9ms) commit transaction (0.2ms) begin transaction SQL (0.2ms) DELETE FROM "credits" WHERE "credits"."id" = ? [["id", 8]] (53.4ms) commit transaction (0.2ms) begin transaction SQL (0.3ms) DELETE FROM "credits" WHERE "credits"."id" = ? [["id", 9]] (53.7ms) commit transaction 2.2.4 :023 > Credit.first.delete Credit Load (0.5ms) SELECT "credits".* FROM "credits" ORDER BY "credits"."id" ASC LIMIT 1 SQL (54.7ms) DELETE FROM "credits" WHERE "credits"."id" = ? [["id", 3]] 2.2.4 :005 > Post.delete_all SQL (73.7ms) DELETE FROM "posts"
时间: 2024-11-08 21:49:51