rails dependent
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rails dependent相关的知识,希望对你有一定的参考价值。
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"
以上是关于rails dependent的主要内容,如果未能解决你的问题,请参考以下文章
Rails :dependent => :destroy VS :dependent => :delete_all
为 memcached 和 Rails 组合片段和对象缓存的最佳方式
ruby RubySteps 012 - Rails - 迷你框架片段