rails-api / active_model_serializers

ActiveModel::Serializer implementation and Rails hooks
MIT License
5.32k stars 1.39k forks source link

serializers not working in nested json #2439

Closed NimaQu closed 1 year ago

NimaQu commented 1 year ago

Expected behavior vs actual behavior

Expected:

{
    "code": 0,
    "message": "0",
    "data": {
        "id": 54,
        "email": "test@test.com"
    }
}

actual:

{
    "code": 0,
    "message": "0",
    "data": {
        "id": 54,
        "email": "nimaqu.dev20@nimaqu.com",
        "created_at": "2022-09-17T03:54:03.422Z",
        "updated_at": "2022-09-17T03:54:23.141Z",
        "jti": "1e58936c-ef85-4447-bcbf-70fd359f110a"
    }
}

Steps to reproduce

(e.g., detailed walkthrough, runnable script, example application) works: render json: user

{
    "id": 54,
    "email": "nimaqu.dev20@nimaqu.com"
}

not working: render json: { code: 0, message: '0', data: user }

{
    "code": 0,
    "message": "0",
    "data": {
        "id": 54,
        "email": "nimaqu.dev20@nimaqu.com",
        "created_at": "2022-09-17T03:54:03.422Z",
        "updated_at": "2022-09-17T03:54:23.141Z",
        "jti": "1e58936c-ef85-4447-bcbf-70fd359f110a"
    }
}

user_serializer.rb:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email
end

Environment

ActiveModelSerializers Version (commit ref if not on tag):

Output of ruby -e "puts RUBY_DESCRIPTION": ruby 2.7.6p219 (2022-04-12 revision c9c2245c0a) [x64-mingw32]

OS Type & Version: Windows 11 Integrated application and version (e.g., Rails, Grape, etc): Rails 5

Backtrace

(e.g., provide any applicable backtraces from your application)

Started GET "/api/v1/client/accounts/brief" for 127.0.0.1 at 2022-11-28 02:26:26 -0600
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 54 LIMIT 1
Processing by UsersController#user_brief as */*
  CACHE User Load (0.0ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 54 LIMIT 1
  ↳ app/controllers/users_controller.rb:31:in `user_brief'
[active_model_serializers] Rendered ActiveModel::Serializer::Null with Hash (0.36ms)
Completed 200 OK in 2ms (Views: 0.9ms | ActiveRecord: 0.0ms | Allocations: 920)

Additonal helpful information

(e.g., Gemfile.lock, configurations, PR containing a failing test, git bisect results)

bf4 commented 1 year ago

Looks like you're using 0.10.x?

That's working as expected. AMS only serializes object. If you render a hash, AMS doesn't process that and it goes to straight to the Rails renderer as documented. If you need to render with AMS outside of the controller's responder, you'll need to invoke it directly as is documented.

Closing as invalid