【问题标题】:Unpermitted parameter in Rails API nested attributesRails API 嵌套属性中不允许的参数
【发布时间】: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,因此创建的许可证没有任何状态。我尝试了不同的方法,但找不到允许状态的方法。请帮忙!

【问题讨论】:

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


【解决方案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

【讨论】:

  • 感谢您的回复。在这种情况下,:code 是一个字符串,所以我无法传递 id。我试图只传递:state 和对象,我也得到与:state_id 时相同的错误@
  • 您不必传递 ID。您传递一个字符串并根据该字符串计算 ID。在将params 转换为state_id 后,您还应该从params 中删除:state(我在回答时错过了这个)。我更新了答案。现在:state在转换为state_id后从params中删除
  • 我做了您建议的更改并得到相同的错误:"undefined method 'iso_abbr' for nil:NilClass" 这是控制台输出的要点。也许你能看到我看不到的东西。 gist.github.com/davidflores2/ca334be415526fd1c03e874d973980c9
  • 在要点代码是错误的!你错过了license.delete(:state)if state从这里复制并正确使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多