2014-01-05 140 views
4

以下railscasts#196但使用Rails 4 - 試圖從問題父模型中刪除答案時遇到問題。刪除嵌套屬性時,未經允許的屬性_destroy

未經許可的參數:_destroy

_answer_fields.html.erb

<fieldset>                                                 
    <%= f.text_field :response %>                                          
    <%= f.hidden_field :_destroy %>                                                                                             
    <%= link_to "remove" , "#", class: "remove_fields" %>                                    
</fieldset>  

question.rb

accepts_nested_attributes_for :questions, :allow_destroy => true 

surveys_controller.rb

def survey_params                                              
    params.require(:survey).permit(:name, :questions_attributes => [:id, :content, :answers_attributes => [:id, :response]])                    
end 

我從表單上刪除字段的罰款,但記錄並沒有被刪除。

感謝

編輯: JS設置隱藏變量

jQuery ->                                                 
     $(document).on 'click' , ".remove_fields" , (event) ->                                    
       $(this).prev('input[type=hidden]').val('1')                                     
       $(this).closest('fieldset').hide()                                       
       event.preventDefault() 

回答

6

@Hitham S. AlQadheeb可能是正確的 - 檢查你的模型是正確的......

survey.rb

class Survey < ActiveRecord::Base 
    has_many :questions, :dependent => :destroy 
    accepts_nested_attributes_for :questions 
end 

question.rb

class Question < ActiveRecord::Base 
    belongs_to :survey 
    has_many :answers, :dependent => :destroy 
    accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true 
end 

但是Unpermitted parameters: _destroy錯誤實際上應該指的是您的控制器的Strong Params實現:survey_params。您需要告訴欄杆您的表格將通過:_destroy字段。試試這個:

def survey_params                                              
    params.require(:survey).permit(:name, :questions_attributes => [:id, :content, :_destroy, :answers_attributes => [:id, :response, :_destroy]])                    
end 
---------------------------------------------------------------------------------^ 
-------------------------------------------------------------------------------------------------------------------------------------^ 
+0

感謝您的幫助!我已經做出了這些改變,我認爲它現在更接近了,我沒有收到任何警告/錯誤。我看到_destroy屬性總是設置爲false - 所以每個db調用我是一個更新,如果你有一個建議,添加我的JS上面。 – MikeW

+0

實際上無視 - 現在得到它的工作,非常感謝和@Hitham S. AlQadheeb – MikeW

+0

這給了我很多悲傷。謝謝! – BKSpurgeon