2011-06-16 74 views
0

我在RoR 2.2項目中使用ActiveScaffold。我在我的應用程序兩種型號:強制ActiveScaffold刪除關聯而不是將外鍵設置爲空

class Foo << ActiveRecord::Base 
belongs_to :bar 
end 

class Bar << ActiveRecord::Base 
has_many :foos 
end 

當我編輯欄實例,屬於該欄中的所有foo的實例顯示在旁邊的每個一個刪除按鈕的形式。

當我刪除一個,然後按下更新按鈕,現在ActiveScaffold設置Foo.bar_id到nil和問題和更新語句,如UPDATE foo set bar_id = null ...

有沒有辦法從數據庫中刪除關聯(即delete foo where foo_id = ...)呢?

+0

這是一個問題ActiveScaffold。它會爲你自動在後臺生成很多東西。現在在我提到的場景中,通過將Foo.bar_id設置爲null來刪除作品。我想從Bar中刪除foo,並將其從數據庫中刪除。 – 2011-06-16 04:42:37

回答

0

像下面這樣的東西應該達到你要找的效果。請記住,我沒有運行或測試此代碼。

class Bar < ActiveRecord::Base 

    has_many :foos, :dependent => :destroy, :after_remove => :delete_orphan 

    def delete_orphan(foo) 
    foo.destroy 
    end 

end 

編輯:切換到更具體的回調

0

我使用這個Rails中3.1。

當我刪除一個文檔時,所有關聯的DocumentFoo也被刪除。

class Document < ActiveRecord::Base 
    has_many :document_foos 

    before_destroy { |record| DocumentFoo.destroy_all "document_id = #{record.id}" } 
end 

BR, 納斯