在我的Rails 7 API应用程序中,我使用jsonapi-serializer
gem进行响应数据序列化。我知道它遵循JSON API标准,但这可以自定义。我有user_serializer
,它产生下面的JSON:
{
"data": {
"id": "8",
"type": "user",
"attributes": {
"email": "[email protected]",
"role": "owner",
"created_at": "2022-10-17T23:59:49.897Z"
},
"links": {
"set_password_url": "some_url"
}
}
}
user_serializer.rb
class UserSerializer
include JSONAPI::Serializer
attributes :email, :role, :created_at
link :set_password_url do |_user, params|
params[:password_url]
end
end
registrations_controller.rb
def create
user = User.new user_params
if user.save
render json: UserSerializer.new(user, { params: { password_url: 'some_url' } } ).serializable_hash
else
(...)
end
end
如何使它简单与此宝石是:
{
"email": "[email protected]",
"role": "owner",
"created_at": "2022-10-17T23:59:49.897Z"
"set_password_url": "some_url" # this attribute is not a User model field
}
我找到了这个答案,但它并没有改变任何事情。
1条答案
按热度按时间y0u0uwnf1#
在你的控制器中添加方法.dig(:data,:attributes),