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!
See Question&Answers more detail:
os