在我的 Rails(仅限 api)学习项目中,我有 2 个模型,Group 和 Artist,它们与加入模型 Role 具有多对多关系,其中包含有关该关系的附加信息。我之前可以通过自己保存连接模型来保存 m2m 关系,但在这里我试图将关系保存为嵌套关系。我正在使用jsonapi-serializer gem,但没有与之结婚,也没有绑定到 JSON api 规范。让它发挥作用比遵循最佳实践更重要。
使用此设置,我在尝试保存时收到 500 错误并出现以下错误:
Unpermitted parameters: :artists, :albums
和ActiveModel::UnknownAttributeError (unknown attribute 'relationships' for Group.)
我怀疑我的问题在于强大的参数和/或 json 有效负载。
楷模
class Group < ApplicationRecord
has_many :roles
has_many :artists, through: :roles
accepts_nested_attributes_for :artists, :roles
end
class Artist < ApplicationRecord
has_many :groups, through: :roles
end
class Role < ApplicationRecord
belongs_to :artist
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
控制器#group_params
def group_params
params.require(:data)
.permit(attributes: [:name, :notes],
relationships: [:artists])
end
序列化器
class GroupSerializer
include JSONAPI::Serializer
attributes :name, :notes
has_many :artists
has_many :roles
end
class ArtistSerializer
include JSONAPI::Serializer
attributes :first_name, :last_name, :notes
end
class RoleSerializer
include JSONAPI::Serializer
attributes :artist_id, :group_id, :instruments
end
示例 JSON 有效负载
{
"data": {
"attributes": {
"name": "Pink Floyd",
"notes": "",
},
"relationships": {
"artists": [{ type: "artist", "id": 3445 }, { type: "artist", "id": 3447 }]
}
}
附加信息
知道我能够使用以下 json 和强参数的组合保存另一个模型可能会有所帮助。
# Example JSON
"data": {
"attributes": {
"title": "Wish You Were Here",
"release_date": "1975-09-15",
"release_date_accuracy": 1
"notes": "",
"group_id": 3455
}
}
# in albums_controller.rb
def album_params
params.require(:data).require(:attributes)
.permit(:title, :group_id, :release_date, :release_date_accuracy, :notes)
end