How do I use Active-record-serializer to compose custom JSON data

204 views Asked by At

I have the following models and serializers. I want a situation that when I make a request to my List Controller index, I get Expected Json. Please see below:

 # GET /lists
  def index
    @lists = current_user.lists

    render json: @lists
  end

See my database association diagram here

Expected JSON

[
    {
        "id": 1,
        "name": "End of Year Party",
        "status": "active",
        "categories": [
            {
                "id": 1,
                "name": "Vegetables",
                "Items": [All items that belong to this category and also belong to this List]
            },
            {
                "id": 2,
                "name": "Fruits",
                "Items": [All items that belong to this category and also belong to this List]
            },
            {
                "id": 24,
                "name": "Medicare",
                "Items": [All items that belong to this category and also belong to this List]
            }
        ],       
    }
]

Models

class Item < ApplicationRecord
 belongs_to :user
 belongs_to :category
 has_many :records
 has_many :lists, through: :records

 validates :name, presence: true, uniqueness: true
 validates :note, :user, :category, presence: true
end

class Category < ApplicationRecord
 has_many :items, dependent: :destroy
 belongs_to :user

 validates :name, presence: true, uniqueness: true
end

class List < ApplicationRecord
 belongs_to :user
 has_many :records, dependent: :destroy
 has_many :items, through: :records

 validates :name, presence: true, uniqueness: true  
end

class Record < ApplicationRecord  (This is the join table for Item and List)
 belongs_to :list
 belongs_to :item
end

Serializers

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :items
end

class ItemSerializer < ActiveModel::Serializer
  attributes :id, :name, :note, :image, :category_name
  belongs_to :category

  def category_name
    object.category.name
  end
end

class ListSerializer < ActiveModel::Serializer
  attributes :id, :name, :status
 
  has_many :items
end

class RecordSerializer < ActiveModel::Serializer
  attributes :id, :quantity
  belongs_to :list
  belongs_to :item
end

I have describe what I tried above.

1

There are 1 answers

0
Leo Policastro On

Rails comes with JBuilder built in.

Check out the docs here: https://github.com/rails/jbuilder