やりたいこと
railsでcocoonというgemを使い一つのフォームから親子孫を一気に保存できるようにしたいのですが、孫の部分で「Unpermitted parameter :grandchildren」が出て、保存に失敗してしまいます。
これを保存できるようにしたいです。
起きてるエラー
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxx", "parent"=>{"name"=>"a", "description"=>"a", "children_attributes"=>{"0"=>{"name"=>"aa", "description"=>"aa", "grandchildren"=>{"name"=>"aaa"}, "_destroy"=>"false"}}}, "commit"=>"投稿する"} Unpermitted parameter: :grandchildren
コード
Model
1class Parent < ApplicationRecord 2 #Childrenとのアソシエーション(1:多) 3 has_many :children 4 accepts_nested_attributes_for :children 5end 6 7class Child < ApplicationRecord 8 #parentsとのアソシエーション(1:多) 9 belongs_to :parent, optional: true 10 11 #Grandchildとのアソシエーション(1:1) 12 has_one :grandchild 13 accepts_nested_attributes_for :grandchild 14end 15 16class Grandchild < ApplicationRecord 17 #childとのアソシエーション(1:1) 18 belongs_to :child 19end
Controller
1class ParentsController < ApplicationController 2 def new 3 @parents = Parent.new 4 @parents.children.build 5 end 6 7 def create 8 @parent = Parent.new(parent_params) 9 #新しい投稿の保存に成功した場合 10 if @parent.save 11 redirect_to parent_path(@parent) 12 #新しい投稿の保存に失敗した場合 13 else 14 #もう一回投稿画面へ 15 redirect_to action: "new" 16 end 17 end 18 19 private 20 def parent_params 21 params.require(:parent).permit(:name, description, children_attributes: [:id, :name, description, :_destroy, grandchildren_attributes: [:id, :name, :_destroy]]) 22 end 23end
View
new
1<%= form_for(@parent, url:{controller:'parents', action:'create'})do |f| %> 2 <div class="field"> 3 <%= f.label :名前%> 4 <%= f.text_field :name, class: 'form-control' %> 5 </div> 6 7 <div class="field"> 8 <%= f.label :説明%> 9 <%= f.text_field :description, class: 'form-control' %> 10 </div> 11 <div id="children"> 12 13 <%= f.fields_for :children do |i| %> 14 <%= render "child_fields", f: i %> 15 <% end %> 16 17 </div> 18<% end %>
_child_fields.html.erb
<div class="field"> <%= f.label :名前%> <%= f.text_field :name, class: 'form-control' %> </div> <div class="field"> <%= f.label :説明%> <%= f.text_field :description, class: 'form-control' %> </div> <div id="children"> <%= f.fields_for :grandchildren do |ii| %> <%= render "grand_child_fields", f: ii %> <% end %>
_grand_child_fields.html.erb
<div class="field"> <%= f.label :名前%> <%= f.text_field :name, class: 'form-control' %> </div>
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。