Search code examples
ruby-on-railsrubyruby-on-rails-5active-model-serializers

Rails 5 API - parent 'must exist' error when trying to create a child record via POST


I'm building my first API (ever) in Rails 5 as a learning experience.

I'm using Rails in --api mode and have the active_model_serializers gem installed.

The API is based on a relationship between ships and voyages.

A ship has_many :voyages and a voyage belongs_to :ship.

Using Postman to check the voyages API endpoint I'm getting this as the return value:

{
  "id": 1,
  "tstd_id": 94583,
  "year": 1722,
  "began": null,
  "trade_began": null,
  "departed_africa": null,
  "arrived_slaves": null,
  "ended": null,
  "length": null,
  "middle_passage_length": null,
  "port_departed": "Liverpool",
  "ship": {
    "id": 1,
    "name": "Mary",
    "flag": "British",
    "rig": null,
    "tonnage": null,
    "standardized_tonnage": null,
    "year_constructed": null,
    "place_registered": null,
    "year_registered": null,
    "from": null,
    "to": null
  }
}

When I try to create a new voyage via POST using Key: voyage[ship][id] Value: 1 I'm getting a return from the API of 'must exist'

The error I'm getting from the Rails console is:

Started POST "/voyages" for 127.0.0.1 at 2016-07-28 11:03:47 +0100
Processing by VoyagesController#create as */*
Parameters: {"voyage"=>{"ship"=>{"id"=>"1"}, "year"=>"4"}}
Unpermitted parameter: ship
(0.2ms)  begin transaction
(0.1ms)  rollback transaction
[active_model_serializers] Rendered ActiveModel::Serializer::Null with ActiveModel::Errors (0.14ms)
Completed 422 Unprocessable Entity in 9ms (Views: 0.9ms | ActiveRecord: 0.4ms)

Any and all help would be greatly appreciated.


Solution

  • If you already have ship's id with you, then you have to send it as ship_id instead of ship[id]. Your parameters should look like,

    { "voyage"=> { "ship_id" => "1", "year" => "4" } }