早上好,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_id
,exhibit_id
和category_id
。
我的问题是,当我删除一个Exhibit时,它的分类表上的引用不会被删除,因此在我的视图中出现DB错误。我必须首先从任何类别取消分配展览,然后安全地删除它。或者(例如,当我放入:exhibit_id=>'1'
rails console
Categorization.find_by_exhibit_id(1).destroy
)
感谢您的帮助!!
答案 0 :(得分:2)
您可以在删除父母时希望Rails遵循的关联设置:dependent
选项:
class Exhibit < ActiveRecord::Base
has_many :categorizations, :dependent => :destroy
...
end