如何通过 Rails 的活动模型序列化程序呈现嵌套对象的父数据?

How to render parent data of nested object via Active model serializers for Rails?

我正在开发 Rails 5 个 api 应用程序。

所以这是我的模型序列化器

class MovieSerializer < ActiveModel::Serializer
  attributes :id ,:name,:release_year,:story,:in_theater,:poster,:score,:user_count

  belongs_to :age_rating
  belongs_to :company
  has_many :categories
  has_many :movie_celebrities

end

class MovieCelebritySerializer < ActiveModel::Serializer
  attributes :id,:vacancy,:title

  belongs_to :celebrity

end

class CelebritySerializer < ActiveModel::Serializer
  attributes :id, :first_name, :last_name

  has_many :movie_celebrities

end

我的控制器

class Api::V1::MoviesController < ApplicationController

  # GET /v1/movies/:id
  def show

    movie = Movie.find_by(id: params[:id])

    render json: movie

  end

end

这就是我得到的

{
  "id": 1,
  "name": "0 The Doors of Perception",
  "release_year": 2007,
  "story": "Non doloribus qui et eum impedit. Rerum mollitia debitis sit nesciunt. Vero autem quae sit aliquid rerum ex fugit. Eligendi assumenda et eos. Blanditiis hic ut. Commodi quo sunt voluptatem quasi.",
  "in_theater": false,
  "poster": "'http://cdn.mos.cms.futurecdn.net/15399e7a7b11a8c2ef28511107c90c6f.jpg',",
  "score": 0,
  "user_count": 6950,
  "age_rating": {
    "id": 2,
    "name": "PG"
  },
  "company": {
    "id": 5,
    "name": "Gislason, Jacobs and Graham"
  },
  "categories": [
    {
      "id": 4,
      "name": "Biography"
    },
    {
      "id": 16,
      "name": "Mystery"
    }
  ],
  "movie_celebrities": [
    {
      "id": 1,
      "vacancy": "director",
      "title": ""
    },
    {
      "id": 2,
      "vacancy": "cast",
      "title": "Pro x"
    },
    {
      "id": 3,
      "vacancy": "cast",
      "title": "Magneto"
    }
  ]
}

问题是我需要像这样在每个 movie_celebrities 对象中包含名人数据。

[
  {
    "id": 1,
    "vacancy": "director",
    "title": "",
    "celebrity": {
      "id": 17,
      "first_name": "Jannie",
      "last_name": "Stiedemann"
    }
  },
  {
    "id": 2,
    "vacancy": "cast",
    "title": "Pro x",
    "celebrity": {
      "id": 56,
      "first_name": "Diego",
      "last_name": "Hickle"
    }
  },
  {
    "id": 3,
    "vacancy": "cast",
    "title": "Magneto",
    "celebrity": {
      "id": 23,
      "first_name": "Myrtie",
      "last_name": "Lebsack"
    }
  }
]

那么我怎样才能让这种情况发挥作用呢? 谢谢!

您应该将 ActiveModelSerializers.config.default_includes = '**' 添加到 config/initializers/active_model_serializers.rb。如果您更喜欢更精细的控制,请参阅文档 here. Or set included 了解正确的渲染方式。