Rails API嵌套属性中未允许的参数

时间:2017-06-16 15:13:36

标签: ruby-on-rails ruby-on-rails-5 rails-api accepts-nested-attributes

我正在尝试使用嵌套字段更新对象,并收到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。我尝试了不同的方法,但找不到允许国家的方法。请帮忙!

1 个答案:

答案 0 :(得分: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