ruby 在POST请求中添加Rails奇怪参数

afdcj2ne  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(77)

我最近意识到,当我试图在POST请求中创建User类的多个项时,会添加一个参数。
我有一些允许的参数:

def user_params
  params.permit(:account_id, users: [:type, :name, :account_id])
end

下面是我在UsersController中的create方法:

def create
  if user_params[:users].blank?
       render status: :no_content
       return
  end

  begin
    _users= User.create!(user_params[:users])
    render json: _users, status: :created
  rescue ActiveRecord::RecordInvalid
    render json: _users.errors, status: :unprocessable_entity
  end
end

当我尝试使用Postman测试时,我使用这些参数:

{
    "users": [{
        "type": "test", 
        "name": "test", 
        "account_id": "2DAC41seuRwGIxTn4PQPZc"
    }, {
        "type": "test2", 
        "name": "test2", 
        "account_id": "2DAC41seuRwGIxTn4PQPZc"
    }]
}

下面是路由器的conf:

resources :account, except: [:index] do
  resources :users, only: [:create, :show, :index]
end

每次我在/accounts/2DAC41seuRwGIxTn4PQPZc/users上执行POST请求时,都会在rails控制台中看到以下参数:
参数:{“users”=>[{“type”=>“test”,“name”=>“test”,“account_id”=>“2DAC41seuRwGIxTn4PQPZc”},{“type”=>“test2”,“name”=>“test2”,“account_id”=>“2DAC41seuRwGIxTn4PQPZc”,}],“account_id”=>“2DAC41seuRwGIxTn4PQPZc”,“user”=>{}}
不允许的参数::用户。
我不知道这个参数从何而来。有人能给我点启发吗?
请注意,我仍然在学习rails和ruby,也许我错过了一些明显的东西。

epggiuax

epggiuax1#

正如@spickerman所提到的,问题是ParamsWrapper期望的是JSON格式,根据doc
如果您启用ParamsWrapper for:json format,[...],它将被 Package 到一个嵌套的散列中,其中的键名与控制器的名称匹配。
然而,即使控制器是复数,模型名称也必须是单数。
我修复了将users列表更改为user的问题:

{
    "user": [{
        "type": "test", 
        "name": "test", 
        "account_id": "2DAC41seuRwGIxTn4PQPZc"
    }, {
        "type": "test2", 
        "name": "test2", 
        "account_id": "2DAC41seuRwGIxTn4PQPZc"
    }]
}

Copyright © 2018 - 2019 www.cnjs.com. All Rights Reserved.粤ICP备16048888号-1粤公网安备4401050200000018号

相关问题