【发布时间】:2015-06-05 01:00:11
【问题描述】:
我有一个评估模型,其中包含许多问题和许多通过问题的答案
class Assessment < ActiveRecord::Base
belongs_to :template
belongs_to :patient
has_many :questions, :through=> :template
has_many :answers, :through=> :questions
accepts_nested_attributes_for :answers
end
class Question < ActiveRecord::Base
belongs_to :template
has_many :answers
end
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :assessment
end
我想创建一个可以接受嵌套属性的评估表。
这是我的评估表:
<%= form_for @assessment do |f| %>
<div role="tabpanel" class="tab-pane active" id="subjective">
<% @assessment.questions.each do |question| %>
<%= render 'question_fields', :question=> question, :f=> f %>
<% end %>
</div>
<%= f.hidden_field :patient_id, :value=> @assessment.patient.id %>
<%= f.hidden_field :template_id, :value=> @assessment.id %>
<%= f.submit 'Save', :class=> "btn btn-primary", :style=>"width: 100%;" %>
<% end %>
还有我的 question_fields:
<p><%= question.content %></p>
<%= f.fields_for :answer do |builder| %>
<div class="row">
<div class="col-sm-10 question">
<% if question.field_type == "text_area" %>
<%= builder.text_area :content, :class=>"form-control" %>
<% end %>
</div>
</div>
最后是我的行动:
def create
@assessment = current_user.assessments.new(assessment_params)
if @assessment.save
redirect_to assessments_path
else
render :new
end
end
protected
def assessment_params
params.require(:assessment).permit(
:template_id, :patient_id,
:answers_attributes => [:id, :question_id, :assessment_id, :tracking, :content])
end
当我提交表单时,我被带到了评估路径,但我的日志显示“未经许可的参数答案”。我知道我的复数形式或关联在某个地方出了问题,但不确定具体在哪里。
【问题讨论】:
-
在
def create正下方粘贴binding.pry并输入params。你看到了什么? -
为什么在允许的情况下在 answers_attributes 的参数中添加 :id?你不应该弄乱 id
标签: ruby-on-rails activerecord nested-forms