2013-08-31 39 views
0

的情況:accepts_nested_attributes_for與關鍵 「_destroy」

class Cellar < ActiveRecord::Base 
    belongs_to :house, dependent: :destroy 

    accepts_nested_attributes_for :house, allow_destroy: true 

    attr_accessible :house_id, :house_attributes, [...] 
end 

class House < ActiveRecord::Base 
    has_one: cellar 
end 

問題:

當我送Cellar形式包括鍵值對"_destroy" => "true"house_attributes內,衆議院被破壞,因爲它應該,但Cellar.house_id未更新爲NULL。

這是正常的行爲嗎?我應該如何解決這個問題?

+0

您的機型混雜聲明。你的'Cellar'模型在父'House'對象上被設置爲'dependent::destroy',但是你希望在房子被銷燬後保留'​​Cellar'對象嗎?這沒有任何意義的IMO。 – zeantsoi

+0

即使我註釋掉'''dependent::destroy''',問題仍然保持不變。 – TomDogg

+0

你的聯繫從根本上是有缺陷的。父母應該接受孩子的嵌套屬性 - 而不是相反。 – zeantsoi

回答

0

爲了完整起見,這裏就是我最後爲了做來解決此問題:

class Cellar < ActiveRecord::Base 
    belongs_to :house, dependent: :destroy 

    accepts_nested_attributes_for :house, allow_destroy: true 

    attr_accessible :house_id, :house_attributes, [...] 

    # I ADDED THIS: 
    before_save :drop_invalid_id 
    def drop_invalid_id 
    self.house_id = nil if house.marked_for_destruction? 
    end 
end 
0

這可能是正常的,這取決於Rails的版本......我認爲直到Rails 3.2時,外鍵在銷燬對象時保持不變是正常的(反之當外鍵更新爲零)。你使用的是什麼版本的Rails?

但是,無論如何,如果你想繼續保持現狀,只需在保存後清理@cellar的外鍵,那麼在成功@cellar.save之後,你總是可以撥打@cellar.reload。這將刷新數據庫中對象@cellar的狀態,並刪除house_id屬性,因爲它不再存在。

+0

我正在使用Rails 3.2.12。但不幸的是,''@ cellar.reload'''不會刪除''''house_id'''(它是與'''house_attributes''和''_destroy'''一起提交的) D b。所以我想我剩下三個選擇:a)zeantsoi的建議(重做模型),或者b)使用JS從表單中刪除'''id''',或者c)從數據庫中刪除它,之後保存。 – TomDogg

+0

糟糕,b)顯然沒有意義。 – TomDogg

相關問題