簡體   English   中英

ActiveRecord:刪除關聯的記錄

[英]ActiveRecord: deleting associated records

我沒有得到的東西

我的模型中有這個:

class Model < ActiveRecord::Base
    has_many :model_options # a link table for many to many
    has_many :options, 
             :through => :model_options, 
             :dependent => :destroy, 
             :foreign_key => 'model_id'
end

我嘗試這樣做:

model = Model.find(id)
model.options.delete # also tried model.options.delete_all

但這不是從數據庫中刪除記錄。 相反,我必須這樣做:

model.options.each do |option|
   option.delete
end

...這不是最好的方法。
那么,最好的方法是什么?

model.options.clear

參考

Garry是對的:model.options.clear

但是,如果需要,您可以進一步將其與模型回調關聯

class Model < ActiveRecord::Base
has_many :model_options # a link table for many to many
has_many :options, 
         :through => :model_options, 
         :dependent => :destroy, 
         :foreign_key => 'model_id'

# Clear options records before destroy
before_destroy :clear_options

protected
  def clear_options
    options.clear
  end
end

或者,您可以使用此插件從數據庫中強制執行FK關系,從而適當地添加數據庫觸發器(如果您的特定數據庫風格支持它們)。

希望對您有幫助

在Rails 3中,您要做的就是:dependent => :destroy和ActiveRecord將負責其余的工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM