AssociationTypeMisMatch:如何使用接受JSON的RESTful API(Rails)创建对象和关联的(嵌套的)对象?

史蒂文

我已经尝试了几个小时,但似乎无法理解自己做错了什么。我出于示例目的简化了示例。

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

添加到Car模型accepts_nested_attributes_for :wheels并将强大的参数更改为

  def car_params
    params.permit(
      :max_speed_in_kmh,
      :name,
      { wheels_attributes: [:id, :place, :thickness_in_cm] }
    )
  end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章