Rails 5 Api使用嵌套资源从json创建新对象 [英] Rails 5 Api create new object from json with nested resource

查看:72
本文介绍了Rails 5 Api使用嵌套资源从json创建新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从外部angular webapp作为参数接收的json:

this is the json received as parameters from external angular webapp:

{
  "provincia": {
    "id": 1,
    "name": "Province"
  },
  "username": "tester",
  "direccion": "new avenue 100",
  "email": "nomail@mail.com"
}

这是我的控制器

 def create
   @seller = Seller.new(seller_params)

  if @seller.save
    render json: @seller, status: :created, location: @seller
  else
    puts @seller.errors.full_messages
    render json: @seller.errors, status: :unprocessable_entity
  end
end

这是Seller_params

this is seller_params

def seller_params
    params.require(:seller).permit(:username, :direccion, :email, :provincia_id)
end

型号:卖方属于Provincia

models: Seller belongs_to Provincia

服务器控制台输出错误完整消息

server console output error full message

Provincia must exist

我应该在Rails API中进行哪些修改才能使其生效并保存新的卖方?预先感谢.

Which modification in the Rails API should I do to make it work, and save the new seller? thanks in advance.

推荐答案

在控制器中允许参数的方式不正确:

轨道文档

您需要在属性中传递provincia_id或允许将要传递给控制器​​的属性

You need to pass your provincia_id in your attributes or permit the attributes that you are passing to your controller

方法1:

{
  "provincia_attributes": {
    "id": 1,
    "name": "Province"
  },
  "username": "tester",
  "direccion": "new avenue 100",
  "email": "nomail@mail.com"
}

SellersController.rb

def seller_params
  params.require(:seller).permit(:username, :direccion, :email, provincia_attributes: [:id, :name])
end

方法2

{
  "provincia_id": "1"
  "username": "tester",
  "direccion": "new avenue 100",
  "email": "nomail@mail.com"
}

SellersController.rb

def seller_params
  params.require(:seller).permit(:username, :direccion, :email, :provincia_id)
end

这篇关于Rails 5 Api使用嵌套资源从json创建新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆