我已经尝试了几个小时,但我似乎不明白我做错了什么。为了便于演示,我简化了我的示例。
单独创建Car
对象是可行的,但将Wheel
对象附加到它会导致ActiveRecord::AssociationTypeMisMatch
。
给定类别汽车和车轮
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
添加到车型accepts_nested_attributes_for :wheels
并将强参数更改为
def car_params
params.permit(
:max_speed_in_kmh,
:name,
{ wheels_attributes: [:id, :place, :thickness_in_cm] }
)
end