user3711600
user3711600

Reputation: 873

Render status and data JSON response with active model serializer

I'm using active model serialiser.

I want to render both 'status' and 'data' in JSON format, e.g.

{"status":"success","data":[{"id":1,"content":xxx"}]}

I've been able to produce the 'data' using the following code in my rails controller:

@jobs = Job.all
render json: @jobs

How can I render both 'status' and 'data'? I've tried doing:

@jobs = Job.all
render :json => { :status => :success, :data => @jobs }

This doesn't recognize my JobSerializer, so renders JSON output, but not with the attributes and associations specified in my JobSerializer.

I've also tried:

@jobs = Job.all
render :json => { :status => :success, :data => ActiveModel::ArraySerializer.new(@jobs, each_serializer: JobSerializer) }

This appears to work, i.e. renders a JSON response with the right attributes speicified in my JobSerializer, but doesn't recognise or render the associations in my JobSerializer (i.e. a has_many association)

Is there an easy way to do this that I'm missing?

Upvotes: 3

Views: 3147

Answers (5)

Kshitij
Kshitij

Reputation: 339

@jobs = Job.all render :json => { :status => :success, :data => (ActiveModel::ArraySerializer.new(@jobs, each_serializer: JobSerializer))

For has_many association to work, the association needs to be defined in both the model and serializer

class JobSerializer < ActiveModel::Serializer
       has_many :association
end

class Section < ApplicationRecord
       has_many :association
end

Upvotes: 0

Atish Maske
Atish Maske

Reputation: 31

  1. Add attr_accessor to your model class

    class Job < ApplicationRecord
    attr_accessor :status

    end

2.Then add same attribute to your serilizer

 class JobSerializer < ActiveModel::Serializer
  attributes :id, :name, :address, :email,:status
  has_one :branch
 end

3.Done add code like this in your controller

@job.status = 'success' render json: @job, status: 200

Upvotes: 0

Pierre Moir&#233;
Pierre Moir&#233;

Reputation: 31

You can do something like:

render :json => {
    status: "success",
    data: ContentSerializer.new( contents ).attributes
}

Upvotes: 3

Pulkit Agarwal
Pulkit Agarwal

Reputation: 594

Try this

@jobs = Job.all
render json: @jobs, status: 200

if above dosent work try this one

@jobs = Job.all
render json: @jobs, status: 200, serializer: JobSerializer

Upvotes: 1

Marko Krstic
Marko Krstic

Reputation: 1447

maybe you can try to render on this way:

@jobs = Job.all
render :json => { :status => :success, :data => @jobs.to_json }

UPDATE:

if you want to render and related objects, this should look like:

render :json => { :status => :success, :data => @jobs.to_json(:include => :users) }

here I assumed that the job model has users

Upvotes: 0

Related Questions