How to convert app to API using serialization
To see one of your model turned into json:
def index
@objects = Object.all
render json: @objects.to_json(:include => :another_object)
end
render json: @objects.to_json(only: [:title, :name, :created_at],
include: [author: {only: [:name]}])
only can be used on the main object and the referenced object!respond_todef index
@objects = Object.all
respond_to do |format|
format.html {render :show}
format.json {render json: @objects.to_json(only: [:title, :name, :created_at],
include: [author: {only: [:name]}])}
end
end
Gemfile: gem 'active_model_serializers'bundle installrails g serializer modelapp/serializersattributes are added to give the serializer more info to return in the JSON response.toJSON... code and just use render json: @objects and that will
call your serializer for that model and display the specified JSON.attributes
, belongs_to @model