RoR 嵌套属性在编辑时会产生重复。

69

我正试图跟随Ryan Bates的RailsCast#196:嵌套模型表单第1部分。与Ryan的版本有两个明显的区别:1)我使用内置的脚手架而不是他使用的nifty,2)我正在运行rails 4(我不知道Ryan在他的录制中使用的是哪个版本,但它不是4)。

所以这是我做的:

rails new survey2
cd survey2
bundle install
rails generate scaffold survey name:string
rake db:migrate
rails generate model question survey_id:integer content:text
rake db:migrate

然后我像这样将关联关系添加到模型中

class Question < ActiveRecord::Base
  belongs_to :survey
end

因此

class Survey < ActiveRecord::Base
  has_many :questions
  accepts_nested_attributes_for :questions
end

然后我添加了嵌套视图部分

<%= form_for(@survey) do |f| %>
  <!-- Standard rails 4 view stuff -->

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.fields_for :questions do |builder| %>
      <div>
        <%= builder.label :content, "Question" %><br/>
        <%= builder.text_area :content, :rows => 3 %>
      </div>
    <% end %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

最后,需要将控制器设置成这样,以便每当实例化一个新的调查时,就会创建3个问题。

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]

  # Standard rails 4 index and show 

  # GET /surveys/new
  def new
    @survey = Survey.new
    3.times { @survey.questions.build }
    Rails.logger.debug("New method executed")
  end

  # GET /surveys/1/edit
  def edit
  end

  # Standard rails 4 create

  # PATCH/PUT /surveys/1
  # PATCH/PUT /surveys/1.json
  def update
    respond_to do |format|
      if @survey.update(survey_params)
        format.html { redirect_to @survey, notice: 'Survey was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @survey.errors, status: :unprocessable_entity }
      end
    end
  end

  # Standard rails 4 destroy

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_survey
      @survey = Survey.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def survey_params
      params.require(:survey).permit(:name, questions_attributes: [:content])
    end
end

因此,创建一个具有三个问题的新调查是可以的。但是,如果我尝试编辑其中一个调查,原始的三个问题将被保留,同时另外创建了三个问题。因此,经过编辑的调查不再是3个问题,而是6个问题。我添加了

Rails.logger.debug("New method executed")

在控制器中使用了新的方法,但据我所知,在执行编辑操作时它并没有被执行。请问我做错了什么?

非常感谢任何帮助!


你能否在你的控制器代码中添加编辑和更新操作,以便我们可以在那里检查错误? - Almaron
当然没问题!我猜在简洁的祭坛上有些东西被遗忘了。 - conciliator
2个回答

164

我不得不在survey_params方法中添加:id到允许的参数中。现在它看起来像这样:

# Never trust parameters from the scary internet, only allow the white list through.
def survey_params
  params.require(:survey).permit(:name, questions_attributes: [:id, :content])
end

这个工作得非常完美。我猜测新的ID被生成了,而不是被传递到更新操作中。


2
非常有用的提示,谢谢!(编辑:只是因为大多数人在解决问题后不会回答自己的问题..) - Robin Kanters
2
当然没问题!我已经多次求助于SO,现在回馈一些东西也是理所应当的。 :) - conciliator
1
我也是RoR的新手。你救了我!我已经花了两天时间在这些嵌套表单上,只是想完成这个相对简单的应用程序。哈哈 - dtc
4
谢谢!这件事情困扰了我好几天,花费了很多时间去搜索。 - user1746971
当然没问题,@timmillwood!偶尔帮助别人总是一种好的感觉。 :) - conciliator
显示剩余2条评论

7

我在Rails 4中使用 gem时,即使在编辑时将:id添加到允许的列表中,仍然会出现重复字段问题。同时注意到以下问题:

Unpermitted parameters: _destroy
Unpermitted parameters: _destroy

因此,我将:_destroy字段添加到允许的model_attributes:字段中,之后事情就顺利进行了。

例如...

def survey_params
  params.require(:survey).permit(:name, questions_attributes: [:id, :content, :_destroy])
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接