jesica
jesica

Reputation: 685

How to show all associated items in json_response in Rails

I'm working on an API based Rails application, I don't know how to show all associated items in one request like my models

todo.rb

class Todo < ApplicationRecord
    has_many :items, dependent: :destroy
    validates_presence_of :title, :created_by
end

item.rb

class Item < ApplicationRecord
    belongs_to :todo
    validates_presence_of :name
end

in the controller

def show
    json_response(@todo)
end

private
def set_todo
    @todo = Todo.find(params[:id])
end

The endpoit for single todo

https://example.com/todos/1

and it showing like this

{
    "id": 1,
    "title": "Hello World!",
    "created_by": "2",
    "created_at": "2018-04-26T11:19:31.433Z",
    "updated_at": "2018-04-26T11:19:31.433Z"
}

My question is how do I show all items which created by this todo in same end point request.

Upvotes: 3

Views: 1361

Answers (2)

Jignesh Gohel
Jignesh Gohel

Reputation: 6552

Try using ActiveModel::Serializers::JSON#as_json

For e.g.

def show
  render json: @user.as_json(include: :posts), status: 200
end

That should return a response like

{
  "id": 1,
  "name": "Konata Izumi",
  "age": 16,
  "created_at": "2006/08/01",
  "awesome": true,
  "posts": [
    {
      "id": 1,
      "author_id": 1,
      "title": "Welcome to the weblog"
    },
    {
      "id": 2,
      "author_id": 1,
      "title": "So I was thinking"
    }
  ]
}

Upvotes: 3

Anand
Anand

Reputation: 6531

def show
  render json: {"todos" => {"todo" => @todo, "items" => @todo.items }}, status:200
end

Alternatively you can use serializers for more filters and modifications of response datas

Upvotes: 1

Related Questions