码迷,mamicode.com
首页 > 其他好文 > 详细

rails dependent

时间:2016-11-19 12:40:45      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:blog   its   select   load   效率   first   active   event   log   

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

标签:blog   its   select   load   效率   first   active   event   log   

原文地址:http://www.cnblogs.com/znsongshu/p/6080185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!