0

我正在使用 Rails 和 Wicked Gem 创建一个多步骤表单。我有一个父子模型。父母有很多孩子,父母形成accepts_nested_attributes_for :children。

我正在控制器的 SHOW 操作上构建一个嵌套对象,以便显示一个表单字段。

出于某种原因,每次保存表单时,数据库中的子项数量(以及视图上的表单字段数量)都会翻倍。首先,它将按预期保存 1 个孩子。然后,如果我回去更新表单的那部分并保存那个孩子,它会创建 2 个孩子,然后是 4 个,等等。

以下是相关代码:

父.rb

class Parent < ApplicationRecord
    belongs_to :user
    has_many :children
    accepts_nested_attributes_for :children
end

子.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 %>
4

1 回答 1

1

您需要将 添加child.id到返回的集合中。如果 rails 没有看到 ID,它会假定这些是新记录。它不必对您可见,但必须是表单的一部分。

<%= f.fields_for :children do |child| %>
  <%= child.hidden_field :id %>

还要确保您的强参数允许:id通过该children_attributes部分。

def parent_params
    params.require(:parent).permit(:spouse_name, :children_attributes => [:id, :full_name])
end
于 2020-01-13T18:14:56.840 回答