У меня есть отношение многие ко многим между projects
и project_category
до project_by_category
.
Мои модели:
Project Model
class Project < ApplicationRecord
# Relationships
has_many :project_by_categories
has_many :project_categories, through: :project_by_categories
ProjectCategory Model
class ProjectCategory < ApplicationRecord
has_many :project_by_categories
has_many :projects, through: :project_by_categories
ProjectByCategory Model
class ProjectByCategory < ApplicationRecord
# Relationships
belongs_to :project
belongs_to :project_category
Мои сериализаторы:
Project Serializer
class ProjectSerializer < ActiveModel::Serializer
attributes :id, :image, :name, :description
Project Category Serializer
class ProjectCategorySerializer < ActiveModel::Serializer
attributes :id, :name
has_many :projects
The expected result:
{
"data": [
{
"id": "1",
"type": "project-categories",
"attributes": {
"name": "3D design basics"
},
"relationships": {
"projects": {
"data": [
{
"id": "1",
"image": "",
"name": "",
"description": "",
"type": "projects"
},
{
"id": "2",
"image": "",
"name": "",
"description": "",
"type": "projects"
}
]
}
}
},
But this is the result:
{
"data": [
{
"id": "1",
"type": "project-categories",
"attributes": {
"name": "3D design basics"
},
"relationships": {
"projects": {
"data": [
{
"id": "1",
"type": "projects"
},
{
"id": "2",
"type": "projects"
}
]
}
}
},
В проекте отношений показывать только идентификатор и тип.
By last this is my controller
class Api::V1::CategoriesController < ApiController
def index
@categories = ProjectCategory.all
render json: @categories
end
Спасибо за ваши ответы !!