ruby-on-railsjson-apijsonapi-resourcesfastjsonapijsonapi-serialize

How to save a nested one-to-many relationship in API-only Rails?


In my Rails (api only) learning project, I have 2 models, Group and Album, that have a one-to-many relationship. When I try to save the group with the nested (already existing) albums, I get the following error, ActiveRecord::RecordNotFound (Couldn't find Album with ID=108 for Group with ID=). I'm using the jsonapi-serializer gem. Below is my current set up. Any help is appreciated.

Models

class Group < ApplicationRecord
  has_many :albums
  accepts_nested_attributes_for :albums
end


class Album < ApplicationRecord
  belongs_to :group
end

GroupsController#create

def create
  group = Group.new(group_params)

  if group.save
    render json: GroupSerializer.new(group).serializable_hash
  else
    render json: { error: group.errors.messages }, status: 422
  end
end

GroupsController#group_params

def group_params
  params.require(:group)
    .permit(:name, :notes, albums_attributes: [:id, :group_id])
end

Serializers

class GroupSerializer
  include JSONAPI::Serializer
  attributes :name, :notes
  has_many :albums
end


class AlbumSerializer
  include JSONAPI::Serializer
  attributes :title, :group_id, :release_date, :release_date_accuracy, :notes
  belongs_to :group
end

Example JSON payload

{
  "group": {
     "name": "Pink Floyd",
     "notes": "",
     "albums_attributes": [
       { "id": "108" }, { "id": "109" }
     ]
  }
}

Solution

  • If the albums already exist, then accepts_nested_attributes is not necessary. You could save them like this:

      Group.new(name: group_params[:name], notes: group_params[:notes], album_ids: group_params[:album_ids])
    

    You will want to extract the album_ids as an array when passing it here.