Steven
Steven

Reputation: 1258

AssociationTypeMisMatch: How can I create an object and associated (nested) objects with RESTful API (Rails) accepting JSON?

I have been trying this for some hours but I cannot seem to understand what I am doing wrong. I simplified my example for demonstration purposes.

Creating the Car object alone works but attaching Wheel objects to it results in an ActiveRecord::AssociationTypeMisMatch.

Given the classes Car and 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

and a 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 } ] }, ...

The JSON is well-formed. Leaving out the wheels, the Car object gets created and persisted. With the Wheel objects though, the controller returns

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)>

Upvotes: 2

Views: 311

Answers (1)

Vasilisa
Vasilisa

Reputation: 4640

If you want to create a car together with wheels you need to use accepts_nested_attributes_for

Add to the Car model accepts_nested_attributes_for :wheels and change strong params to

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

Upvotes: 3

Related Questions