ActiveRecord:删除关联记录

6

有些地方我没有理解...

我的模型中有这个内容:

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

...这不可能是最好的方法。
那么,请问什么是最好的方法?

3个回答

10

4

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

或者,您可以使用这个插件来从数据库添加适当的DB触发器(如果您的特定数据库支持它们),以强制执行FK关系。

希望这可以帮助您。


好奇,如果你已经使用了 :dependent => :destroy 选项,那么 before_destroy 回调是否必要? - Joshua Pinter
不是的。它无法启动Rails 3。 - Derk-Jan

1
在Rails 3中,你只需要使用:dependent => :destroy,ActiveRecord会处理其余的事情。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接