0

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

楷模

class Group < ApplicationRecord
  has_many :albums
  accepts_nested_attributes_for :albums
end


class Album < ApplicationRecord
  belongs_to :group
end

组控制器#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" }
     ]
  }
}
4

1 回答 1

0

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

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

在此处传递它时,您需要将专辑 ID 作为一个数组提取。

于 2020-11-02T05:41:10.890 回答