如何从所引用的所有表中删除记录?

时间:2011-07-30 11:13:12

标签: ruby-on-rails-3 model refinerycms model-associations

早上好,Overflowers,

模型关联的小问题。我有这些模型关联:

class Categorization < ActiveRecord::Base
  belongs_to :exhibit
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :categorizations
  has_many :exhibits, :through => :categorizations
  acts_as_indexed :fields => [:title]
  validates :title, :presence => true, :uniqueness => true 
end

class Exhibit < ActiveRecord::Base
  has_many :categorizations
  has_many :categories, :through => :categorizations, :source => :category
  acts_as_indexed :fields => [:title, :bulb]
  validates :title, :presence => true, :uniqueness => true
  belongs_to :foto, :class_name => 'Image'
end

因此,基本上Categorization最终会显示这些列(省略日期/时间戳): categorization_idexhibit_idcategory_id

我的问题是,当我删除一个Exhibit时,它的分类表上的引用不会被删除,因此在我的视图中出现DB错误。我必须首先从任何类别取消分配展览,然后安全地删除它。或者(例如,当我放入:exhibit_id=>'1' rails console

时,我删除的图表有Categorization.find_by_exhibit_id(1).destroy

感谢您的帮助!!

1 个答案:

答案 0 :(得分:2)

您可以在删除父母时希望Rails遵循的关联设置:dependent选项:

class Exhibit < ActiveRecord::Base
  has_many :categorizations, :dependent => :destroy
  ...
end