ActiveRecord:删除相关记录

时间:2009-05-07 12:22:50

标签: ruby-on-rails activerecord

我没有得到的东西......

我的模型中有这个:

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 个答案:

答案 0 :(得分:10)

model.options.clear

Reference

答案 1 :(得分:4)

加里是对的:     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

或者您可以使用this plugin来强制实施FK关系,从数据库中添加数据库触发器(如果您的特定数据库风味支持它们)。

我希望maight帮助你

答案 2 :(得分:1)

在Rails 3中,你所要做的只是:dependent => :destroy而ActiveRecord会处理其余的事情

相关问题