【问题标题】:Rails Strong Params & Nested Forms: "Unpermitted parameter: answer"Rails 强参数和嵌套表单:“不允许的参数:答案”
【发布时间】: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


【解决方案1】:

试一试,您的 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

【讨论】:

  • 在这种情况下我将如何构建表单?因为我目前没有为该问题提交任何字段。
  • 最坏的情况,您可以在问题上创建一个attr_accessor :dummy 虚拟变量并传递一个随机字符串。这将创建question_attributes 键并允许在问题上嵌套answer_attributes
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多