0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Serializer】ActiveRecordを継承していないモデルのJSONレスポンスを整形したい

Posted at

###返したいレスポンス

本のタグ一覧API

{
  "book_tags": [
    {
      "id": 1,
      "name": "芥川賞受賞"
    },
    {
      "id": 2,
      "name": "ベストセラー"
    },
    {
      "id": 3,
      "name": "映画化決定"
    }
  ]
}

ActiveRecordを継承していないBookTagモデルのJSONは整形しないとこうなる。

{
  {
    "id": 1,
    "name": "芥川賞受賞"
  },
  {
    "id": 2,
    "name": "ベストセラー"
  },
  {
    "id": 3,
    "name": "映画化決定"
  }
}

###Serializerを使わずにコントローラーでJSONを整形

class BookTagsController < Api::ApplicationController
  def index
    tags = Tag.all
    hash = { "book_tags" => tags }
    json_str = JSON.pretty_generate(hash)
    render json: json_str
  end
end

###最終形態
もっと簡単に書けた。

class BookTagsController < Api::ApplicationController
  def index
    tags = Tag.all
    render json: { book_tags: tags }
  end
end

##参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?