1

我有三个模型:

class Answer < ActiveRecord::Base
  belongs_to :question
  belongs_to :profile
  belongs_to :theme
  has_many :linked_sources

  attr_accessible :body, :theme_id, :question_id, :linked_sources_attributes
  validates_presence_of :body, :profile, :question, :theme
  has_paper_trail :on => [:update]

  accepts_nested_attributes_for :linked_sources, reject_if: :all_blank
end

class Answer::LinkedSource < ActiveRecord::Base
  belongs_to :answer
  belongs_to :source

  validates :source, :description, presence: true
  validates_presence_of :answer_id, :unless => :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_sources 仍然存在。服务器端只是忽略“_destroy”参数。

怎么了?我在这个项目中为另一个具有更简单嵌套(只有一层)的模型提供了另一种茧形式,它工作正常,但在另一种情况下却不行。

(如你所见,我的英语并不完美——对此感到抱歉——如果你能改正就好了)

4

1 回答 1

1

您必须添加allow_destroy: true到协会的accepts_nested_attributes_for

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

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

于 2012-05-17T12:10:01.163 回答