2012-05-16 40 views
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」參數。

怎麼了?在這個項目中,我爲另一個模型提供了另一個繭形式,它具有簡單的嵌套(只有一個層次),並且工作正常,但是在另一種情況下它沒有。

(正如你可以看到,我的英語是不完美的 - 對此感到遺憾 - 這將是罰款,如果你更正)

回答

1

您必須添加allow_destroy: true到該協會的accepts_nested_attributes_for

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

請參閱docs for more details