Help us understand the problem. What is going on with this article?

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

モデルのインスタンスを 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

https://github.com/YumaInaura/YumaInaura/issues/3050

YumaInaura
Ruby on Rails 業務経験 約5年 / Perl PHP Python Golang Linux Apache MySQL BigQuery Jenkins ansible AWS など / いなうらゆうま / YumaInaura / 稲浦悠馬
http://twitter.com/yumainaura
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away