嵌套强参数错误

时间:2014-12-12 14:18:05

标签: ruby-on-rails ruby

我们正在尝试创建一个具有一个地址的用户。地址是另一个模型,具有“has_one / belongs_to”关系。 这是我们收到的json

{ "user": {
  "username": "Dave",
  "password": "superpass",
  "password_confirmation": "superpass",
"email": "dave@gmail.com",
"email2": "dave2@gmail.com",
"firstname": "Bob",
"lastname": "Bave",
"birthdate": "02-07-94",
"address": {
"address": "15 landing street",
"zipcode": "75018",
"city": "Paris",
"country": "France"
}
}}

并且我们的控制器具有强大的参数。

class UsersController < ApplicationController
  before_action :authenticate, only: :update

  def create
    begin
      p user_params_create[:address_attribute]
      u = User.new(user_params_create)
      u.address = Address.new(user_params_create[:address_attribute])
      u.save
      head :created
    rescue ActiveRecord::RecordNotUnique => e
      Rails.logger.error e.message
      head :bad_request
    end
  end

  def update
    u = User.find_by(id: params[:id])
    u.update_attributes(user_params_update)
  end

  private
  def user_params_create
    params.require(:user).permit(:username, :email, :email2, :firstname, :lastname, :birthdate, :password, :password_confirmation, :address_attribute => [:address, :zipcode, :city, :country])
  end

  def user_params_update
    params.require(:user).permit(:username, :email, :email2, :firstname, :lastname, :birthdate, :address => [:address, :zipcode, :city, :country])
  end
end

用户的创建有效,但地址的字段为零。 知道为什么吗?

2 个答案:

答案 0 :(得分:2)

好的,我们通过将json修改为

来解决它
{ "user": {
  "username": "Dave",
  "password": "superpass",
  "password_confirmation": "superpass",
"email": "dave@gmail.com",
"email2": "dave2@gmail.com",
"firstname": "Bob",
"lastname": "Bave",
"birthdate": "02-07-94",
"address_attributes": {
"address": "15 landing street",
"zipcode": "75018",
"city": "Paris",
"country": "France"
}
}}

在其中添加“address_attributes。控制器现在可以看到所有参数。请向nicooga求助!

答案 1 :(得分:1)

param的名称是未命中的类型。将其更改为:

def user_params_create
  params.require(:user).permit(:username, :email, :email2, :firstname,
   :lastname, :birthdate, :password, :password_confirmation,
   :address => [:address, :zipcode, :city, :country])
end

你有

Address(#70254790661320) expected, got ActionController::Parameters(#70254756417360)`

因为,设置者User#address=期望Address对象没有你给它的params哈希值。

要启用通过父级初始化嵌套模型,您应该使用accepts_nested_attributes_for :address,然后使用setter address_attributes

class User
  accepts_nested_attributes_for :address
end

User.new(name: 'Roger', bleh: 'asdf',
  address_attributes: { zip: 213123, etc: 2 })

检查http://apidock.com/rails/ActiveRecord/NestedAttributes/ClassMethods/accepts_nested_attributes_for

请记住白名单正确的attrs:

def user_params_create
  params.require(:user).permit(:username, :email, :email2, :firstname,
   :lastname, :birthdate, :password, :password_confirmation,
   address_attributes: [:address, :zipcode, :city, :country])
end