【问题标题】:Strong parameters for nested attributes are ignored嵌套属性的强参数被忽略
【发布时间】:2014-08-27 18:08:50
【问题描述】:

我正在尝试使用字符串参数来允许传入模型的嵌套属性,无论出于何种原因,permit 方法都会忽略任何嵌套的内容。见下文:

型号:

class User < ActiveRecord::Base
  accepts_nested_attributes_for :phone_number, :address, update_only: true
  accepts_nested_attributes_for :profession, update_only: true
end

控制器:

class Api::V1::Users::UsersController < Api::BaseController
  def update
    permitted = permitted_user_params
  end

  def permitted_user_params
    params.require(:profile).permit(
      :first_name,
      :last_name,
      :password,
      :password_confirmation,
      phone_number_attributes: [:phone_number],
      address_attributes: [:street, :city, :province, :country, :postal_code],
      profession_attributes: [:company, :title, :designation]
    )
  end
end

如果我传入格式正确的数据, allowed_user_params 将不会返回除first_name, last_name, password and password_confirmation 以外的任何值。

谁能告诉我我做错了什么?

谢谢

【问题讨论】:

  • 我想你忘记了嵌套模型的 id:phone_number_attributes: [:id, :phone_number], address_attributes: [:id, :street, :city, :province, :country, :postal_code], profession_attributes: [:id, :company, :title, :designation]
  • 每个都包含:id似乎没有任何效果。
  • 你想出这个了吗?我看到了同样的事情。
  • @MFrazier - 请参阅下面的答案。

标签: ruby-on-rails-4 nested-attributes strong-parameters


【解决方案1】:

我发现了我的错误。当您发布到端点时,您的数据需要与 rails 端的预期格式相匹配。对于上面的示例,您需要发布您的数据,例如:

{
    profile: {
        first_name,
        last_name,
        password,
        password_confirmation,
        phone_number_attributes: {
            phone_number
        },
        address_attributes: {
            street,
            city,
            province,
            country,
            postal_code
        },
        profession_attributes: {
            company,
            title,
            designation
        }
    }
}

Rails 显式查找末尾值为 _attributes 的键,如果找不到任何内容,它会继续执行,不会为您清理这些属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多