我在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属性( string),只回答: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
发布于 2015-08-24 03:33:24
问题在于你的question_params
。应该如下所示
def question_params
params.require(:question).permit(:text, alternativas_attributes: [:id, :texto, :question_id])
end
https://stackoverflow.com/questions/32172338
复制相似问题