LoginSignup
41
23

More than 5 years have passed since last update.

Active Model Serializerで深くネストした関連を含めたい

Last updated at Posted at 2016-09-14

追記:バージョンは0.10.2

Active Model Serializerで再帰的に関連を含んだjsonを出したかったが、
デフォルト設定では、深さが1までしか関連を含んでくれないため、想定通りに出なかった。

serializers

class HogeSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_one :fuga
end
class FugaSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_one :piyo
end
class PiyoSerializer < ActiveModel::Serializer
  attributes :id, :name
end

欲しいjson

{
    "hoge": {
        "id": 1,
        "name": "ほげ",
        "fuga": {
            "id": 1,
            "name": "ふが",
            "piyo": {
                "id": 1,
                "name": "ぴよ"
            }
        }
    }
}

実際に出力されたjson

{
    "hoge": {
        "id": 1,
        "name": "ほげ",
        "fuga": {
            "id": 1,
            "name": "ふが"
            # piyoがない!
        }
    }
}

解決するには、ActiveModelSerializers.config.default_includes = '**'のように設定してやると良い。
https://github.com/rails-api/active_model_serializers/pull/1426

ちなみにデフォルトは、'*'

'**'ってなんなん、、、

追記

全体に設定したくない場合は、controller側でのrenderincludeをつけてやればできる。

class HogeController < ApplicationController
  def index
    @hoge = # 略
    render json: @hoge, include: ['fuga', 'fuga.piyo']
    #                or include: 'fuga,fuga.piyo'
  end
end

参考→ https://github.com/rails-api/active_model_serializers/blob/master/docs/general/adapters.md#included

上記のURLにも記述があるが、*の意味は以下のように定義されているらしい
- *は深さ1までの関連を含む
- **は深さすべて再帰的に関連を含む

なので、すべての関連を含めたいときは、以下のように書いてやると簡単に書ける

class HogeController < ApplicationController
  def index
    @hoge = # 略
    render json: @hoge, include: '**'
  end
end

さらに、指定したモデル以下のすべての関連を出したいときは以下のようにも書ける

class HogeController < ApplicationController
  def index
    @hoge = # 略
    render json: @hoge, include: 'fuga.**'
  end
end
41
23
2

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
41
23