How to render a json with the json_api adapter using Rails Serializer?

Asked

Viewed 315 times

0

Oops, I’d like to render a json using the json_api standard (http://jsonapi.org/) using Rails Serializer(https://github.com/rails-api/active_model_serializers).

In my controller I’m rendering something similar to this:

render json: {'user': {name: 'Peter' }}

However, when I rewrite this JSON, it is not coming out in json_api format.

In other Controllers/Models the serializers are working correctly, since they are using Activerecord, but in this case I cannot pass an Activerecord and would like to keep the outputs of my api standardized.

** Note: I cannot pass the Activerecord in this controller because it does not have a table.

Can you help me?

  • Welcome to Stackoverflow in English. As the name suggests, the official language used here is Portuguese. So, could you please translate your question? If you prefer, you can also ask the same question on Stackoverflow website in English

  • Ops, translated.

2 answers

0

I didn’t understand the "In other Controllers/Models serializers are working properly, since they are using Activerecord".

Are these other models already serialized? If so, you should already see a difference in Response for these models. Post the Sponse for these cases for us to take a look.

The default Rails template to render JSON is the class ActiveSupport::JSON and not the ActiveRecord.

But by default to configure AMS(Activemodelserializers) with JSON:API specification you need:

  • Add AMS Gem to no Gemfile gem 'active_model_serializers', '~> 0.10.0'
  • Rotate a bundle install
  • Create a file in PASTA_DO_PROJETO/config/initializers/ams.Rb(can be any name instead of ams.Rb) and add the following line: ActiveModelSerializers.config.adapter = :json_api # Default: :attributes. This line will tell AMS to make JSON specification user:API
  • Create the Serialize for models chosen with the command rails g serializer MODEL_NAME.

The SHOW method of yours users_controller.Rb might be something like:

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :update, :destroy]
  ...
  ...
  # GET /users/1
  def show
    render json: @user
  end
  ...
  ...
  private
   # Use callbacks to share common setup or constraints between actions.
   def set_user
     @user = User.find(params[:id])
   end

   def user_params
     ActiveModelSerializers::Deserialization.jsonapi_parse(params)
   end
end

And authorize attributes in the being user_serializer.Rb and put desired settings:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email, :outro_atributo

  belongs_to :alguma_associação
  has_many :outra_associação
  has_one :alguma_outra_associação
end

I hope I’ve helped.

0

  • I tried it here, in this way not right. It keeps rendering only JSON, without json_api structure

Browser other questions tagged

You are not signed in. Login or sign up in order to post.