ruby-on-rails - AssociationTypeMisMatch:如何使用接受 JSON 的 RESTful API (Rails) 创建对象和关联(嵌套)对象?
问题描述
我已经尝试了几个小时,但我似乎无法理解我做错了什么。出于演示目的,我简化了我的示例。
Car
单独创建对象是可行的,但将Wheel
对象附加到它会导致ActiveRecord::AssociationTypeMisMatch
.
给定 Car 和 Wheel 类
class Car < ApplicationRecord
has_many :wheels
validates :max_speed_in_kmh,
:name, presence: true
end
class Wheel < ApplicationRecord
has_one :car
validates :thickness_in_cm,
:place, presence: true
end
和一个 CarsController
module Api
module V1
class CarsController < ApplicationController
# POST /cars
def create
@car = Car.create!(car_params)
json_response(@car, :ok)
end
private
def car_params
params.permit(
:max_speed_in_kmh,
:name,
{ wheels: [:place, :thickness_in_cm] }
)
end
end
end
end
echo '{"name":"Kid","max_speed_in_kmh":300,"wheels":[{"thickness_in_cm":70, "place":"front"},{"thickness_in_cm":75, "place":"rear"}]}' | http POST httpbin.org/post
...
"json": {
"max_speed_in_kmh": 300,
"name": "Kid",
"wheels": [
{
"place": "front",
"thickness_in_cm": 70
},
{
"place": "rear",
"thickness_in_cm": 75
}
]
},
...
JSON 格式正确。离开轮子,Car
对象被创建并持久化。但是,对于Wheel
对象,控制器返回
status 500
error Internal Server Error
exception #<ActiveRecord::AssociationTypeMismatch: Wheel(#70285481379180) expected, got {"place"=>"front", "thickness_in_cm"=>75} which is an instance of ActiveSupport::HashWithIndifferentAccess(#70285479411000)>
解决方案
如果你想和轮子一起创建汽车,你需要使用accepts_nested_attributes_for
添加到 Car 模型accepts_nested_attributes_for :wheels
并将强参数更改为
def car_params
params.permit(
:max_speed_in_kmh,
:name,
{ wheels_attributes: [:id, :place, :thickness_in_cm] }
)
end
推荐阅读
- amazon-web-services - 从上传到 S3 的文件触发的无服务器框架和 AWS Step Functions(AWS 状态机)
- python-3.x - PyWAVES:simplejson.errors.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)
- javascript - module.export 正在导出对象而不是存储在变量中的字符串
- python - 从 Python 中的嵌套字典中按顺序排序和打印键和值
- javascript - 更改嵌套函数内的变量值
- c# - 如何使用 C# 9.0 新委托*将方法从 C# 9.0 正确发送到 C/C++ 库?
- java - 如何使用 Selenium 和 Java 从 Chrome 获取控制台日志
- javascript - 最多等待 N 秒以等待某事发生
- kubernetes - 使用 Kubernetes 容器原生负载均衡和 GCP Standalone NEG 实现网络负载均衡
- python-3.x - 在 python 中使用 selenium 查找特定标签