无法破坏现有的嵌套关联

我有三个型号:

class Answer  [:update] accepts_nested_attributes_for :linked_sources, reject_if: :all_blank end class Answer::LinkedSource  :nested attr_accessor :nested accepts_nested_attributes_for :source, reject_if: :all_blank, allow_destroy: true end class Source < ActiveRecord::Base SOURCE_TYPES = %w(book film) has_many :linked_sources, class_name: 'Answer::LinkedSource' has_many :answers, through: :linked_sources validates :source_type, inclusion: {in: SOURCE_TYPES} validates :source_type, :title, presence: true end 

我有一个表单,其中包含已存在的两个嵌套已存在的链接源+源。 在我的_linked_source_fields部分我有link_to_remove_association并且它正常工作,将“_destroy”输入的值设置为“1”。

当我删除两个资源并按下提交按钮时,我会发送以下表单数据:

 utf8:✓ _method:put authenticity_token:726c1e7NIb0Je2uUZYeKLXmqgFHxgakfcF6fzpjFb38= answer[theme_id]:2 answer[body]:retert _wysihtml5_mode:1 answer[question_id]:22 answer[linked_sources_attributes][0][source_id]:3 answer[linked_sources_attributes][0][nested]: answer[linked_sources_attributes][0][source_attributes][source_type]:book answer[linked_sources_attributes][0][source_attributes][title]:erger answer[linked_sources_attributes][0][source_attributes][id]:3 answer[linked_sources_attributes][0][description]:erger ter answer[linked_sources_attributes][0][_destroy]:1 answer[linked_sources_attributes][0][id]:3 answer[linked_sources_attributes][1][source_id]:4 answer[linked_sources_attributes][1][nested]: answer[linked_sources_attributes][1][source_attributes][source_type]:film answer[linked_sources_attributes][1][source_attributes][title]:terter answer[linked_sources_attributes][1][source_attributes][id]:4 answer[linked_sources_attributes][1][description]:retr answer[linked_sources_attributes][1][_destroy]:1 answer[linked_sources_attributes][1][id]:4 commit:Готово 

这似乎是正确的数据。

但是在保存此表单后,两个linked_source仍然存在。 服务器端只是忽略“_destroy”参数。

怎么了? 我有另一个模型用于另一个模型,在这个项目中具有更简单的嵌套(只有一个级别)并且它工作正常,但在另一种情况下它没有。

(你可以注意到,我的英语并不完美 – 对不起 – 如果你能纠正它会好的)

您必须将allow_destroy: true添加到关联的accepts_nested_attributes_for

 accepts_nested_attributes_for :linked_sources, reject_if: :all_blank, allow_destroy: true 

有关更多详细信息,请参阅文档 。