【问题标题】:Rails update_attributes causing object to be duplicated every time it hits update controller actionRails update_attributes 导致对象在每次更新控制器操作时都被复制
【发布时间】:2020-01-13 18:08:32
【问题描述】:

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

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

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

以下是相关代码:

parent.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 %>

【问题讨论】:

    标签: ruby-on-rails update-attributes wicked-gem


    【解决方案1】:

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

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

    还要确保您的强参数允许 :idchildren_attributes 部分传递。

    def parent_params
        params.require(:parent).permit(:spouse_name, :children_attributes => [:id, :full_name])
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多