Search code examples
ruby-on-railsnested-attributesdestroy

accepts_nested_attributes_for with key "_destroy"


The situation:

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

The problem:

When I send the Cellar form and include the key-value pair "_destroy" => "true" inside the house_attributes, the House gets destroyed as it should, but the Cellar.house_id is not updated to NULL.

Is this normal behavior? How should I best fix this?


Solution

  • For the sake of completeness, here's what I ended up doing in order to correct the issue:

    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