前提・実現したいこと
rails APIを使って、category_nameを入力すると、登録したカテゴリーのideaを一覧表示させる機能を作成したい。
active_model_serializerを利用して、json形式で以下のような値をレスポンスで返したい。
"{ ""data"": [ { ""id"": 1, ""category"": ""映画"", ""body"": ""勝手にふるえてろ"" }, { ""id"": 2, ""category"": ""映画"", ""body"": ""桐島部活やめるってよ"" } ] }"
やりたいこと
①serializerを利用した上で、GETメソッドをリクエストしたときのjson形式のオブジェクトをdataという配列に入れてレスポンスを返したい。
②オブジェクトのkeyとvalue(文字列のみ)に二重のダブルクォーテーションを付けたい。
###現状のレスポンス(in Postman)
[ { "id": 10, "body": "\"コウノドリ\"", "category": "\"漫画\"" }, { "id": 9, "body": "\"NARUTO\"", "category": "\"漫画\"" }, { "id": 8, "body": "\"ワンピース\"", "category": "\"漫画\"" }, { "id": 7, "body": "\"終末のワルキューレ\"", "category": "\"漫画\"" } ]
dataに入っていない。(controllerのrender部分で工夫したが、serializer)
valueの値に特殊文字のエスケープで使った、バッククォーテーションが表示されしまっている
該当のソースコード
ideas_controller.rb
ruby
1module Api 2 module V1 3 class IdeasController < ApplicationController 4 before_action :set_idea, only: [:show, :update, :destroy] 5 6 7 def index 8 category = Category.find_by(name: params[:category_name]) 9 if category.present? 10 @ideas = Idea.search(category).order(created_at: :desc).includes(:category) 11 render json: @ideas 12 else 13 render status: 404, json: { status: 404, message: "Idea Not Found" } 14 end 15 end 16 17 18 def create 19 @category = Category.find_or_create_by(name: params[:category_name]) 20 idea = Idea.new(idea_params) 21 if idea.save 22 render status: 201, json: {message: "Created"} 23 else 24 render status: 422, json: {message: "Unprocessable Entity" } 25 end 26 end 27 28 29 private 30 def set_idea 31 @idea = Idea.find(params[:id]) 32 end 33 34 def idea_params 35 params.permit(:body).merge(category_id: @category.id) 36 end 37 end 38 end 39end 40
idea_serializer.rb
ruby
1module Api 2 module V1 3 class IdeaSerializer < ActiveModel::Serializer 4 attributes :id, :body, :category 5 6 belongs_to :category 7 8 def id 9 return object.id 10 end 11 12 def body 13 body = "\"#{object.body}\"" 14 body.gsub(/\/){ '' } 15 end 16 17 def category 18 category = Category.find_by(id: object.category_id) 19 category_name = "\"#{category.name}\"" 20 category_name.gsub(/\/){ '' } 21 end 22 23 end 24 end 25end 26
idea.rb
ruby
1class Idea < ApplicationRecord 2 belongs_to :category 3 4 validates :body, presence: true 5 6 class << self 7 def search(category) 8 Idea.where(category_id: category.id) 9 end 10 end 11end 12
category.rb
ruby
1 2class Category < ApplicationRecord 3 has_many :ideas 4 5 validates :name, presence: true 6 7end
schema.rb
ruby
1 2ActiveRecord::Schema.define(version: 2020_04_26_083205) do 3 4 create_table "categories", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| 5 t.string "name", null: false 6 t.datetime "created_at", null: false 7 t.datetime "updated_at", null: false 8 end 9 10 create_table "ideas", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t| 11 t.text "body", null: false 12 t.bigint "category_id" 13 t.datetime "created_at", null: false 14 t.datetime "updated_at", null: false 15 t.index ["category_id"], name: "index_ideas_on_category_id" 16 end 17 18 add_foreign_key "ideas", "categories" 19end 20
routes.rb
ruby
1Rails.application.routes.draw do 2 # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html 3 namespace 'api', format: :json do 4 namespace 'v1' do 5 resources :ideas 6 resources :categories 7 end 8 end 9end 10
試したこと
controllerのindexアクションのrender部分で、
ruby
1render json: {data: @ideas}, each_serializer: :IdeaSerializer, root: nil
とした場合、
{ "data": [ { "id": 10, "body": "\"コウノドリ\"", "category_id": 7, "created_at": "2020-04-27T02:52:18.000Z", "updated_at": "2020-04-27T02:52:18.000Z" }, { "id": 9, "body": "\"NARUTO\"", "category_id": 7, "created_at": "2020-04-27T02:47:47.000Z", "updated_at": "2020-04-27T02:47:47.000Z" }, { "id": 8, "body": "ワンピース", "category_id": 7, "created_at": "2020-04-27T02:39:59.000Z", "updated_at": "2020-04-27T02:39:59.000Z" }, { "id": 7, "body": "終末のワルキューレ", "category_id": 7, "created_at": "2020-04-27T02:38:16.000Z", "updated_at": "2020-04-27T02:38:16.000Z" } ] }
となって、serializerを介さずに、そのままideasのデータが出力されてしまう。
補足情報(FW/ツールのバージョンなど)
active_model_serializers (0.10.10)
rails (~> 5.2.4, >= 5.2.4.2)
mysql2 (0.5.3)
RUBY VERSION
ruby 2.6.2p47
BUNDLED WITH
1.17.2
あなたの回答
tips
プレビュー