关注railscast#196但使用Rails 4 - 我在尝试从问题父模型中删除答案时遇到了问题。
未经许可的参数:_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()
答案 0 :(得分: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
错误实际上应该指的是您的控制器对强参数的实现:survey_params
。您需要告诉rails您的表单将通过:_destroy
字段。试试这个:
def survey_params
params.require(:survey).permit(:name, :questions_attributes => [:id, :content, :_destroy, :answers_attributes => [:id, :response, :_destroy]])
end
---------------------------------------------------------------------------------^
-------------------------------------------------------------------------------------------------------------------------------------^
答案 1 :(得分:1)
应该是
question.rb
belongs_to :survey
has_many :answers, : dependent => :destroy
accepts_nested_attributes_for :answers, :allow_destroy => true
再看一遍http://railscasts.com/episodes/196-nested-model-form-part-1