Rails と Wicked Gem を使用して、複数ステップのフォームを作成しています。親モデルと子モデルがあります。親には多くの子があり、親の形式は accept_nested_attributes_for :children です。
フォーム フィールドが表示されるように、コントローラーの SHOW アクションでネストされたオブジェクトを構築しています。
何らかの理由で、フォームが保存されるたびに、データベース内の子の数 (およびビュー上のフォーム フィールドの数) が 2 倍になります。まず、予想どおり 1 人の子を保存します。次に、フォームのその部分を更新してその子を保存すると、2 つの子が作成され、次に 4 つというようになります。
関連するコードは次のとおりです。
親.rb
class Parent < ApplicationRecord
belongs_to :user
has_many :children
accepts_nested_attributes_for :children
end
child.rb
class Child < ApplicationRecord
belongs_to :parent
end
parent_steps_controller.rb
class ParentStepsController < ApplicationController
include Wicked::Wizard
steps :spouse, :children
def show
@user = current_user
if Parent.find_by(id: params[:parent_id])
@parent = Parent.find(params[:parent_id])
session[:current_parent_id] = @parent.id
else
@parent = Parent.find_by(id: session[:current_parent_id])
end
@parent.children.build
render_wizard
end
def update
@parent = Parent.find_by(id: session[:current_parent_id])
@parent.update_attributes(parent_params)
render_wizard @parent
end
private
def parent_params
params.require(:parent).permit(:spouse_name, :children_attributes => [:full_name])
end
end
children.html.erb
<%= form_for(@parent, :url=> wizard_path, :method => :put) do |f| %>
<h1>Children Information</h1>
<%= f.fields_for :children do |child| %>
<div class="field">
<%= child.label :full_name %>
<%= child.text_field :full_name %>
</div>
<% end %>
<%= f.submit "Continue", :class => "btn btn-primary" %>
<% end %>