我是rails的新手,也是Stackoverflow的新手,所以请耐心等待。我确信除了我当前的查询之外还有一些事情没有正确完成。
我有一个应用程序,其中包含有问题和提交的matricies,并且提交的内容有嵌套的答案(对于matricies中的问题)。
我有一个表单供用户提交提交,其中显示特定矩阵的所有相关问题,并允许用户回答它们。这一切都在数据库中的提交/答案表中正确呈现和保存。
但是,当我编辑提交时,它正确地使用先前输入的数据预填充字段,以便该部分正常工作,但是当我保存它时,只需复制它。
我确信我在我的关系声明中犯了一些错误,因为提交应该只允许对每个问题给出答案,但我已经绕圈了好几个小时,很可能在错误的地方找工作。
您可以在此处查看效果:http://digital-maturity-matrix.herokuapp.com/matrices/1/submissions/2
我的模特:
class Submission < ActiveRecord::Base
belongs_to :matrix
belongs_to :user
has_many :answers, :dependent => :destroy
accepts_nested_attributes_for :answers,
:allow_destroy => true
end
我的控制器:
def edit
@matrix = Matrix.find(params[:matrix_id])
@submission = Submission.find(params[:id])
@answers = @submission.answers
@questions = @matrix.questions
end
def update
@matrix = Matrix.find(params[:matrix_id])
@user_id = current_user
respond_to do |format|
if @submission.update(submission_params)
format.html { redirect_to matrix_submission_path(@matrix,@submission), notice: 'Submission was successfully updated.' }
format.json { render :show, status: :ok, location: @submission }
else
format.html { render :edit }
format.json { render json: @submission.errors, status: :unprocessable_entity }
end
end
end
...
def submission_params
params.require(:submission).permit(:matrix_id, :user_id, :name, :answers_attributes => [:question_answered, :choice, :question_id])
end
我的表格:
= form_for([@matrix,@submission]) do |f|
- if @submission.errors.any?
#error_explanation
%h2
= pluralize(@submission.errors.count, "error")
prohibited this submission from being saved:
%ul
- @submission.errors.full_messages.each do |message|
%li= message
%br/
.field
= f.hidden_field :matrix_id, :value => params[:matrix_id]
.field
= f.hidden_field :user_id, :value => current_user.id
= f.fields_for :answers, @answers do |answer|
.field
=answer.label answer.object.question_answered
= answer.text_field :choice
.field
= answer.hidden_field :question_answered
.field
= answer.hidden_field :question_id
.actions
= f.submit
答案 0 :(得分:3)
在发布此消息后的几秒钟内,我找到了答案。我认为写这个问题的过程有所帮助。
对于偶然发现这一点的其他人,我错过了包含:我的嵌套属性中的id允许参数。我没有意识到这是必须的。
所以我需要更换:
def submission_params
params.require(:submission).permit(:matrix_id, :user_id, :name, :answers_attributes => [:question_answered, :choice, :question_id])
end
使用:
def submission_params
params.require(:submission).permit(:matrix_id, :user_id, :name, :answers_attributes => [:id, :question_answered, :choice, :question_id])
end
谢谢大家, TB