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.
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
– Sorack
Ops, translated.
– Vitor