Rails 4 嵌套表单未在参数中传递嵌套属性

Rails 4 Nested Form not Passing Nested Attributes in Params

当我提交表单时,它在参数中传递 {"utf8"=>"✓", "authenticity_token"=>"blah", "client"=>{"first_name"=>"jack", "last_name"=>"kool","complaints"=>{"symptom"=>"burnt"},我得到 Unpermitted Parameters: complaints 因为投诉嵌套在客户端中,它应该传递 complaints_attributes,就像我有它设置在强大的参数中,我不明白为什么不是。

class ClientsController < ApplicationController

 def new
  @client = Client.new
 end

 def edit
  @client = Client.find(params[:id])
 end

 def create
  @client = Client.new(client_params)

  if @client.save
   redirect_to @client
  else
   render 'new'
  end  
end

def update
 @client = Client.find(params[:id])

 if @client.update(client_params)
  redirect_to @client
 else
  render 'edit'
 end
end

private

 def client_params
   params.require(:client).permit(:first_name, :last_name, complaints_attributes: [ :symptom, :id ])
 end
end

客户端模型:

class Client < ActiveRecord::Base
 has_many :complaints
 has_one :personal_disease_history
 has_one :family_disease_history
 has_many :surgeries
 has_many :hospitalizations
 has_many :medications
 has_many :allergies

 validates :first_name, :last_name, presence: true

 accepts_nested_attributes_for :complaints
end

投诉模型:

class Complaint < ActiveRecord::Base
 belongs_to :client
end

表格:

<%= form_for :client, url: clients_path, html: { class: "form-inline" } do |f| %>
 <div class="panel panel-success">
  <div class="panel-heading">
   <h3 class="panel-title">Health History Form</h3>
  </div>
 <div class="panel-body">
  <div class="form-blocks"><legend>Name</legend>
    <div class="form-group">
      <%= f.label :first_name, class: "sr-only" %>
      <%= f.text_field :first_name, class: "form-control", placeholder: "First Name"  %>
    </div>
    <div class="form-group">
      <%= f.label :last_name, class: "sr-only" %>
      <%= f.text_field :last_name, class: "form-control", placeholder: "Last Name"  %>
    </div>
  </div>
  <div class="form-blocks"><legend>Complaints</legend>
    <div class="form-group">
      <%= f.fields_for :complaints do |builder| %>
        <%= builder.label :symptom, class: "sr-only" %>
        <%= builder.text_field :symptom, class: "form-control", placeholder: "Symptom"  %>
      <% end %>
    </div>
  </div>
 <div>
  <%= f.submit "Submit Form", class: "btn btn-primary btn-lg"%>
 </div>
<% end %>

在客户端控制器中创建操作,尝试在 if @client.save:

中这样说
Complaint.create(symptom: params[
"client"]["complaints"]["symptom"], client_id: @client.id)

不允许的参数与嵌套属性问题有关,但这应该得到实际的记录保存。如果不行,请 post 围绕提交的堆栈跟踪。

还有其他一些想法:但是 (1) 您在允许的参数中有 complaint_attributes,但您可以将其更改为投诉 bc 这就是参数中的内容。