Brian Wang
Brian Wang

Reputation: 83

Custom Json Response using Active model serializers

I am getting a response from using a custom serializers like:

render json: @required_user, :serializer => CustomuserSerializer

I want a Json somthing like this:

render json: { status: 'Success', message: "User Created Successfully", data: @required_user, :serializer => CustomuserSerializer }

How can i achieve this? Searched over on stackoverflow to find solutions that are not working..

Upvotes: 1

Views: 1351

Answers (1)

Aarthi
Aarthi

Reputation: 1521

Write a common method for success like below and this can be used in all places.

    def render_success_response(data: nil, message: nil, serializer_options: {})
      resp_data = { status: 'success' }
      resp_data[:message] = message if message
    
      # Serialize the resource
      resp_data[:data] = ActiveModelSerializers::SerializableResource.new(data, serializer_options)if data
    
      render json: resp_data, status: 200
    end
  • data is the active record relation or active record object to be serialized. In your case - @required_user
  • message - Success message to be sent in the response. in here - "User Created Successfully"
  • serializer_options - serialization options needed. Like serializer, each_serializer, include and other options.

Upvotes: 3

Related Questions