如何在仅API的Rails中保存嵌套的一对多关系?

问题描述

在我的Rails(仅限api)学习项目中,我有2个模型,即Group和Album,它们具有一对多的关系。当我尝试使用嵌套(已存在)相册保存该组时,出现以下错误ActiveRecord::RecordNotFound (Couldn't find Album with ID=108 for Group with ID=)。我正在使用jsonapi-serializer宝石。以下是我当前的设置。任何帮助表示赞赏。

模型

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

序列化器

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

示例JSON有效负载

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

解决方法

如果相册已经存在,则不需要accepts_nested_attributes。 您可以这样保存它们:

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

在将其传递到此处时,您将需要将album_ids提取为数组。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...