Rails 7 delete data attribute from jsonapi-serializer

498 views Asked by At

In my Rails 7 API app I'm using jsonapi-serializer gem for response data serialization. I know it follows the JSON API standard however this can be customised. I've got user_serializer which produces below 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

How to make it simple with this gem to be:

{
  "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
}

I found this answer but it didn't change anything.

1

There are 1 answers

0
Daniel Peñaloza On

Hi in your controller just add the method .dig(:data, :attributes),

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