0

我正在尝试使用嵌套字段更新对象并收到Unpermitted parameters错误消息。导致错误的字段本身就是与嵌套表中另一个表的关系。以下是具体情况:

博士班

class Doctor < User
    has_many :professional_licenses, dependent: :destroy
    has_many :states, through: :professional_licenses
    accepts_nested_attributes_for :professional_licenses, allow_destroy: true
   ...
end

专业执照等级

class ProfessionalLicense < ApplicationRecord
  belongs_to :doctor
  belongs_to :state

  validates_presence_of :code
end

国家级

class State < ActiveRecord::Base
  validates_presence_of :iso_abbr, :name
end

医生控制器

...
def update
  doctor = @current_user
  params[:doctor][:professional_licenses_attributes].each do |license, index|
    license[:state] = State.find_by_iso_abbr license[:state]
  end
  doctor.update_attributes(doctor_params)
  render json: doctor, status: :ok
end
...
def doctor_params
  params.require(:doctor).permit(:email, :first_name, :last_name, :password, 
  :password_confirmation, professional_licenses_attributes: [:code, :state, :_destroy])
end

来自 UI 的调用如下所示:

{
"doctor":{
    "first_name":"Doctor Postman",
    "professional_licenses_attributes": [
        {
            "code": "NY-1234",
            "state": "NY"
        },
        {
            "code": "MA-1234",
            "state": "MA"
        }
    ]
}
}

当我发送呼叫时,记录正在更新并创建许可证。但是,由于控制器说,许可证在没有状态的情况下创建Unpermitted parameters: state。我尝试了不同的方法,但找不到允许状态的方法。请帮忙!

4

1 回答 1

1

在您的情况下,code参数应该是一个简单的值,例如整数或字符串。但是您将其转换为对象,还必须将其属性添加到允许的列表中。

尝试传递code_id(整数)而不是code(对象):

...
def update
  doctor = @current_user
  params[:doctor][:professional_licenses_attributes].each do |license|
    state = State.find_by_iso_abbr(license.delete(:state))
    license[:state_id] = state.id if state
  end
  doctor.update_attributes(doctor_params)
  render json: doctor, status: :ok
end
...
def doctor_params
  params.require(:doctor).permit(:email, :first_name, :last_name, :password, 
  :password_confirmation, professional_licenses_attributes: [:code, :state_id, :_destroy])
end
于 2017-06-16T22:48:04.783 回答