実現したいこと
1:多の関係となっているplansテーブルとplan_detailsテーブルにデータを格納するフォームを作成したい
困っていること
cocoonによる動的なフォームの追加は実現できたが、
追加されたフォームに入力された情報がリクエストに乗っておらずサーバー側で受け取れない状況です。
想定しているリクエスト
Parameters: {"authenticity_token"=>"[FILTERED]",
"plan"=>{"title"=>"test",
"plan_details_attributes"=>
{"0"=>{"id"=>"", "title"=>"1", "description"=>""},
"1"=>{"id"=>"", "title"=>"2", "description"=>""}}}, "commit"=>"登録する"}
実際に投げられているリクエスト
Parameters: {"authenticity_token"=>"[FILTERED]",
"plan"=>{"title"=>"test",
"plan_details_attributes"=>
{"0"=>{"id"=>"", "title"=>"1", "description"=>""}}}, "commit"=>"登録する"}
→cocoonよって追加されたフォームの明細が設定されない
画面の初期表示時から設定されているフォームに入力された値については、
正常にリクエストに設定されており、テーブル登録まで可能なことを確認しています。
該当箇所のソース
new.html.erb
<div id="plan_info">
<h1>しおりの情報</h1>
<%= form_for @plan do |plan| %>
<div>
<%= plan.label :title, "タイトル" %>
<%= plan.text_area :title, required: true %>
</div>
</div>
<div>
<h1>予定</h1>
<%= link_to_add_association '明細を追加', plan, :plan_details,
data: {association_insertion_node: '#detail-association-insertion-point',
association_insertion_method: 'append' } %>
<%= plan.fields_for :plan_details do |detail|%>
<%= render 'plan_detail_fields', f: detail %>
<% end %>
<div id='detail-association-insertion-point'></div>
</div>
<%= plan.submit %>
<% end %>
_plan_detail_fields.html.erb
<div class="nested-fields">
<%= f.hidden_field :id %>
<div>
<%= f.label :title, "タイトル" %>
<%= f.text_area :title, required: true %>
</div>
<div>
<%= f.label :description, "詳細" %>
<%= f.text_area :description %>
</div>
</div>
plans_controller.rb
class PlansController < ApplicationController
def new
@plan = Plan.new
@plan.plan_details.build
end
def create
@plan = Plan.new(plan_params)
if @plan.save
redirect_to plan_path(@plan)
else
render action: 'new'
end
end
private
def plan_params
params.require(:plan).permit(:title, plan_details_attributes: [:id,:plan_id,:title,:description])
end
end
以上です。よろしくお願いします。