Rails Strong Params&嵌套表格:"未经许可的参数:回答"

时间:2015-06-05 01:00:12

标签: ruby-on-rails activerecord nested-forms

我有一个评估模型,通过问题有很多问题和很多答案

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 %>

我的问题字段:

<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

当我提交表单时,我会被带到assessment_path,但我的日志显示&#34;未经许可的params回答&#34;。我知道某个地方我的复数或关联出了问题,但不确定到底在哪里。

1 个答案:

答案 0 :(得分:0)

给这一点,看起来你accepts_nested_attributes_for :answers位于错误的地方而你错过questions的那个。

class Assessment < ActiveRecord::Base
  belongs_to :template
  belongs_to :patient
  has_many :questions, :through=> :template
  has_many :answers, :through=> :questions
  accepts_nested_attributes_for :questions
end

class Question < ActiveRecord::Base
  belongs_to :template
  has_many :answers
  accepts_nested_attributes_for :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
  belongs_to :assessment
end