2011-07-30 132 views
1

早上好夥伴外溢者,如何從所涉及的所有表中刪除記錄?

模型關聯的小問題。我有這些模型關聯: categorization_idexhibit_idcategory_id

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這些列(省略日期/時間標記)結束。

我的問題是,當我刪除一個Exhibit時,它對Categorization表的引用不會被刪除,因此在我的視圖中會出現數據庫錯誤。我必須先取消任何類別的展覽,然後將其安全地刪除。或者(舉例來說,圖表I刪除有:exhibit_id=>'1')當我在rails consoleCategorization.find_by_exhibit_id(1).destroy

感謝您的任何幫助!

回答

2

你可以設置你想要的Rails協會:dependent選項時所遵循刪除他們的父母:

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

...我們有贏家!謝謝你,卡斯帕它像一個魅力工作.. – Cacofonix

相關問題