はじめに ここ半年ぐらいActiveModel::Serializersを使った開発をしていて 痒い所に手が届く書き方をいくつか見つけたので紹介していきます 基本的な使い方はすでにいろんな方の記事があるので省略します 1. キー名を変えたい id first_name last_name employee_number といったカラムを持つUserモデルがあったときに first_nameをnameとして出力したい場合 a. :keyオプションを使う class UserSerializer < ActiveModel::Serializer attributes :id, :employee_number attribute :first_name, key: :name end
Returns a hash representing the model. Some configuration can be passed through options. The option include_root_in_json controls the top-level behavior of as_json. If true, as_json will emit a single root node named after the object’s type. The default value for include_root_in_json option is false. user = User.find(1) user.as_json # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, # "creat
user.as_json(methods: :permalink) # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, # "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true, # "permalink" => "1-konata-izumi" } user.as_json(include: :posts) # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, # "created_at" => "2006-08-01T17:27:13.000Z", "awesome" => true, # "posts" => [ { "id" => 1, "author_id" => 1, "title" =>
概要 gem active_model_serializers の version 0-10-stable のドキュメントを翻訳しました。 Rails で API を作成するときに active_model_serializers を使うことも多いと思うので、参考になれば幸いです。 翻訳について 翻訳サービス Deepl と Goole翻訳 の訳文を参考にしている箇所があります。 ライセンスについて active model serializers のライセンスと同様に、MIT ライセンスに従います。 目次 Adapters 原文 Built in Adapters Attributes(デフォルト) 出力例 JSON 出力例 JSON API 出力例 Include オプション セキュリティに関する考慮事項 高度なアダプタの設定 アダプタを登録する アダプタの検索 Caching 原文
class Hoge < ApplicationRecord has_many :fugas end class Fuga < ApplicationRecord has_many :bars end class Bar < ApplicationRecord end # app/serializers/hoge_seralizer.rb class HogeSerializer < ActiveModel::Serializer attributes :id, :hogehoge has_many :fugas class FugaSerializer < ActiveModel::Serializer attributes :id, :fugafuga has_many :bars class BarSerializer < ActiveModel::Serializer attrib
リリース、障害情報などのサービスのお知らせ
最新の人気エントリーの配信
処理を実行中です
j次のブックマーク
k前のブックマーク
lあとで読む
eコメント一覧を開く
oページを開く