问题描述
在我的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提取为数组。