Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
YumaInaura opened this issue Mar 28, 2020 · 0 comments

Comments

@YumaInaura
Copy link
Owner

モデルのインスタンスを 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\":\"吾輩\"}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant