2
1

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.

#Rails / Controller 以外で ActiveModelSerializers の動作確認、JSON出力をする ( rails console とか )

Last updated at Posted at 2020-03-28

モデルのインスタンスを Serializer に与えて to_json するだけで良さげ

Serializer

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
end

動作

空のインスタンス

user = User.new

# <User:0x000055cfd1dcf6f8
#   id: nil,
#   name: nil,
#   email: nil,
#   created_at: nil,
#   updated_at: nil>

serialized_user = UserSerializer.new(user)

serialized_user.to_json
# => "{\"id\":null,\"name\":null}"

DBからインスタンスを得る例

user = User.last

# #<User:0x000055cfd1ea0730
#  id: 19,
#  name: "吾輩",
#  created_at: Fri, 20 Mar 2020 01:02:10 UTC +00:00,
#  updated_at: Fri, 20 Mar 2020 01:02:10 UTC +00:00>


serialized_user = UserSerializer.new(user)

serialized_user.to_json
# => => "{\"id\":19,\"name\":\"吾輩\"}"

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?