문제

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?

도움이 되었습니까?

해결책 2

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

다른 팁

This may be normal depending on the version of Rails... I think up until Rails 3.2 it was normal for the foreign key to remain untouched when destroying object (and vice versa when updating a foreign key to nil). What version of Rails are you using?

But, regardless, if you want to keep going as is and just clean up the foreign key on @cellar after saving then you can always just call @cellar.reload after the successful @cellar.save. This would refresh the state of your @cellar object from the database and remove the house_id attribute since it's no longer present.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top