LoginSignup
2
2

More than 3 years have passed since last update.

Rails 6で認証認可入り掲示板APIを構築する #9 serializer導入

Last updated at Posted at 2020-09-14

Rails 6で認証認可入り掲示板APIを構築する #8 seed実装

ActiveModelSerializerの導入

serializerを入れることで、jsonで返されるデータを簡単に整形できます。

Gemfile
...

+ # serializer
+ gem "active_model_serializers"
$ bundle

設定ファイルとserializerの編集

導入できたらpostモデルのserializerと、ActiveModelSerializerの設定ファイルも作ります。

$ rails g serializer post
$ touch config/initializers/active_model_serializer.rb
app/serializers/post_serializer.rb
# frozen_string_literal: true

#
# post serializer
#
class PostSerializer < ActiveModel::Serializer
  attributes :id
end
config/initializers/active_model_serializer.rb
# frozen_string_literal: true

ActiveModelSerializers.config.adapter = :json
app/controllers/v1/posts_controller.rb
     def index
       posts = Post.order(created_at: :desc).limit(20)
-      render json: { posts: posts }
+      render json: posts
     end

     def show
-      render json: { post: @post }
+      render json: @post
     end

     def create
       post = Post.new(post_params)
       if post.save
-        render json: { post: post }
+        render json: post
       else
         render json: { errors: post.errors }
       end
@@ -27,7 +27,7 @@ module V1

     def update
       if @post.update(post_params)
-        render json: { post: @post }
+        render json: @post
       else
         render json: { errors: @post.errors }
       end
@@ -35,7 +35,7 @@ module V1

     def destroy
       @post.destroy
-      render json: { post: @post }
+      render json: @post
     end

一旦ここまでやったらrails sを止めて、再起動しましょう。

curlで確認

$ curl localhost:8080/v1/posts 
{"posts":[{"id":20},{"id":19},{"id":18},{"id":17},{"id":16},{"id":15},{"id":14},{"id":13},{"id":12},{"id":11},{"id":10},{"id":9},{"id":8},{"id":7},{"id":6},{"id":5},{"id":4},{"id":3},{"id":2},{"id":1}]}
$ curl localhost:8080/v1/posts/1
{"post":{"id":1}}

serializerでidのみにしているので、idの一覧が取得できました。
それではsubject, bodyを追加してみます。

app/serializers/post_serializer.rb
 # frozen_string_literal: true

 #
 # post serializer
 #
 class PostSerializer < ActiveModel::Serializer
-  attributes :id
+  attributes :id, :subject, :body  
 end
$ curl localhost:8080/v1/posts
{"posts":[{"id":20,"subject":"無駄","body":"ハチのすさいぼうかっこう。暴力血液恨み。秘めるちゅうもんする廃墟。"},...
curl localhost:8080/v1/posts/1
{"post":{"id":1,"subject":"hello","body":"警官総括大尉。めいしぼきんかたみち。伝統徳川超〜。

正常に動いていそうですね。
rubocopとrspecも動かして、問題なければcommitしておきましょう。

続き

Rails 6で認証認可入り掲示板APIを構築する #10 devise_token_auth導入
連載目次へ

2
2
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
2
2