【发布时间】:2017-06-16 15:13:35
【问题描述】:
我正在尝试使用嵌套字段更新对象并收到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,因此创建的许可证没有任何状态。我尝试了不同的方法,但找不到允许状态的方法。请帮忙!
【问题讨论】:
-
你能在
.each循环前后检查你的params吗? -
哪个不允许的参数?请显示完整的错误/日志。
-
@Gerry 我得到的错误是
{"message":"undefined methodiso_abbr' for nil:NilClass"}. theiso_abbrr` 是该表中州的缩写。这也是控制台输出gist.github.com/davidflores2/2818385e1f217456d6a2bac40e4b00d5 -
@PavelMikhailyuk 这里是之前和之后的参数:gist.github.com/davidflores2/6e5f73612b43a5df4e724fcc4927bd32
标签: ruby-on-rails ruby-on-rails-5 rails-api accepts-nested-attributes