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

梦想与她 提交于 2019-12-12 03:49:26

问题


I am working on Rails 5 api only app.

So this is my model serializer

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

My controller

class Api::V1::MoviesController < ApplicationController

  # GET /v1/movies/:id
  def show

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

    render json: movie

  end

end

So this is what i got

{
  "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"
    }
  ]
}

By the problem is i need a celebrity data inside each movie_celebrities object like this.

[
  {
    "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"
    }
  }
]

So how can i make this situation working? Thanks!


回答1:


You should add ActiveModelSerializers.config.default_includes = '**' to config/initializers/active_model_serializers.rb. See documentation here. Or set included for render right way in case you prefer more granular control.



来源:https://stackoverflow.com/questions/40002720/how-to-render-parent-data-of-nested-object-via-active-model-serializers-for-rail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!