使用 accepts_nested_attributes_for 的正确方法和在 Rails 中更新记录的构建方法是什么?

What's the correct way of using the accepts_nested_attributes_for and the build methods for updating record in Rails?

我在 Xubuntu 机器上使用 Rails 4.1.4。我有一个问题模型,它有很多备选方案(我的语言可能的答案),如下所示:

# question.rb
class Question < ActiveRecord::Base
  has_many :alternativas, dependent: :destroy
  validates_presence_of :text
  accepts_nested_attributes_for :alternativas, reject_if: proc {|attributes| attributes[:texto].blank? }
end

# alternativa.rb
class Alternativa < ActiveRecord::Base
  belongs_to :question
end

问题只有:text 属性(字符串),答案只有:texto 属性(也是字符串)。我可以创建一个问题,但是当我尝试编辑它时,它只会编辑问题文本,而不是答案。创建新答案而不是更新旧答案。

此外,由于 :text 字段是必需的,当我将其留空时,它会重定向到与错误消息相同的页面,但由于某些奇怪的原因,所有答案都会加倍(如果我提交时只有一个答案表格,当它显示错误信息时会有 2 个相同的答案)。

那么我该如何解决这两个问题呢?我的猜测是我没有正确使用构建和 accepts_nested_attributes_for 方法,所以这是我的控制器:

class QuestionsController < ApplicationController
  before_action :set_question, only: [:show, :edit, :update, :destroy]
  before_filter :authorize
  before_filter :verify_admin

  def index
    @questions = Question.all
  end

  def show
  end

  def new
    @question = Question.new
    @question.alternativas.build # I also tried 5.times { @question.alternativas.build } for 5 answers text fields
  end

  def edit 
  end

  def create
    @question = Question.new(question_params)

    respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render :show, status: :created, location: @question }
      else
        format.html { render :new }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    respond_to do |format|
      if @question.update(question_params)
        format.html { redirect_to @question, notice: 'Question was successfully updated.' }
        format.json { render :show, status: :ok, location: @question }
      else
        format.html { render :edit }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @question.destroy
    respond_to do |format|
      format.html { redirect_to questions_url, notice: 'Question was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
  def set_question
    @question = Question.find(params[:id])
  end

  def question_params
    params.require(:question).permit(:text, { alternativas_attributes: [:texto, :question_id] })
  end
end

问题出在您的 question_params 上。应该像下面这样

def question_params
  params.require(:question).permit(:text, alternativas_attributes: [:id, :texto, :question_id])
end