ruby Rails 7从jsonapi-serializer中删除数据属性

mrzz3bfm  于 2023-10-17  发布在  Ruby
关注(0)|答案(1)|浏览(84)

在我的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
}

我找到了这个答案,但它并没有改变任何事情。

y0u0uwnf

y0u0uwnf1#

在你的控制器中添加方法.dig(:data,:attributes),

render json: UserSerializer.new(user, { params: { password_url: 'some_url' } } ).serializable_hash.dig(:data, :attributes)

相关问题