Rails 4允许使用动态键嵌套嵌套

时间:2018-07-06 08:46:48

标签: ruby-on-rails-4

在参数中使用动态键允许嵌套哈希时遇到的问题。我已经提到了其他有关堆栈溢出的类似问题,但到目前为止还没有运气。任何帮助是极大的赞赏。下面是引发的错误。

ActionController :: UnpermittedParameters 找到了不允许的参数:自愿者槽位属性,sign_up_slots_attributes

{"event"=>{
"name"=>"ss", 
"volunteers_slots_attributes"=>{
"0"=>{"_destroy"=>"false", "needed_count"=>""},
"1"=>{"_destroy"=>"false", "needed_count"=>""},
... 
}, 
"sign_up_slots_attributes"=>{
"0"=>{"_destroy"=>"false", "title"=>"", "quantity"=>""}, 
"1"=>{"_destroy"=>"false", "title"=>"", "quantity"=>""}, 
"2"=>{"_destroy"=>"false", "title"=>"", "quantity"=>""},
 .... 
}, 
"supplies_note"=>""}}

控制器:

 def event_params
    params[:event].permit(:name,:supplies_note,
    :volunteers_slots_attributes,
    :sign_up_slots_attributes)
 end

事件模型:

  accepts_nested_attributes_for :sign_up_slots, allow_destroy: true, reject_if: :all_blank
  accepts_nested_attributes_for :volunteers_slots, allow_destroy: true, reject_if: :all_blank

3 个答案:

答案 0 :(得分:1)

您必须像

那样更改强大的参数

params.require(:event).permit( :name, :supplies_note, volunteers_slots_attributes: [ :_destroy, :needed_count ], sign_up_slots_attributes: [ :_destroy, :title, :quantity ] )

答案 1 :(得分:0)

您需要确保event.rb模型文件具有嵌套属性。

在您的情况下,它应包含如下几行:

accepts_nested_attributes_for :volunteers_slots, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :sign_up_slots, reject_if: :all_blank, allow_destroy: true
# ...

答案 2 :(得分:0)

您总是可以使用params[:event].permit(:name: volunteers_slots_attributes: ['0', '1'])之类的东西来允许嵌套属性。