← Building a bulletin board API with certification authorization in Rails 6 # 8 seed implementation
By including serializer, you can easily format the data returned by json.
Gemfile
...
+ # serializer
+ gem "active_model_serializers"
$ bundle
Once installed, create a post model serializer and an ActiveModelSerializer configuration file.
$ 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
Once you've done this, stop rails s
and restart.
$ 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}}
I was able to get a list of ids because only ids are used in serializer. Now let's add subject and 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":"Useless","body":"The bee's cuckoo. Violent blood grudge. The hidden ruins."},...
curl localhost:8080/v1/posts/1
{"post":{"id":1,"subject":"hello","body":"Captain General Police Officer. Meishibokin Katamichi. Traditional Tokugawa super ~.
It seems to be working normally. Let's also run rubocop and rspec and commit if there is no problem.
→ Introduce # 10 devise_token_auth to build bulletin board API with authentication authorization in Rails 6 [To the serial table of contents]