如何在 API-only Rails 中保存嵌套的一对多关系?
How to save a nested one-to-many relationship in API-only Rails?
在我的 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
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 时,您需要将其提取为数组。
在我的 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
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 时,您需要将其提取为数组。