Rails Serializer Association - PullRequest
       1

Rails Serializer Association

0 голосов
/ 04 июля 2018

У меня есть класс Component, который может быть Section или Question. A Section может иметь множество Component (т.е. Question).

Я пытаюсь заставить сериализатор отправить обратно Component (Section) и связанный с ним Component (Question). Прямо сейчас, основываясь на моем коде ниже, я получаю обратно объект Question и Section, с которым он связан (см. Ниже). Как я могу заставить сериализатор вернуть то, что я ожидаю?

Ответ (текущий):

{"data":
  [{"id": 1,
    "type": "Section",
    "content": "ABC",
    "section_id": null,
    "section": null
   },
   {"id": 2,
    "type": "Question",
    "content": "Q1",
    "section_id": 1,
    "section": 
      {"id": 1,
       "type": "Section",
       "content": "ABC",
       "section_id": null
      }
   },
   {"id": 3,
    "type": "Question",
    "content": "Q2",
    "section_id": 1,
    "section": 
      {"id": 1,
       "type": "Section",
       "content": "ABC",
       "section_id": null
      }
   }]
}

Ответ (ожидается):

{"data":
  [{"id": 1,
    "type": "Section",
    "content": "ABC",
    "section_id": null,
    "section": 
       {"id": 2,
        "type": "Question",
        "content": "Q1",
        "section_id": 1
       },
       {"id": 3,
        "type": "Question",
        "content": "Q2",
        "section_id": 1
       }
   }]
}

ComponentSerializer:

class ComponentSerializer < ActiveModel::Serializer

  belongs_to :section

  attributes :id,
         :type,
         :content,
         :section_id
end

SectionSerializer:

class ComponentSerializer < ActiveModel::Serializer

  has_many :components

  attributes :id,
         :type,
         :content,
         :section_id
end

component.rb (модель):

class Component < ApplicationRecord

  # == Associations ==========================
  belongs_to :project
  belongs_to :section,
    class_name: 'Section',
    foreign_key: :section_id,
    optional: true

end

section.rb (модель):

class Section < Component

  # == Associations ==========================
  has_many :components,
    class_name: 'Component',
    foreign_key: :component_id,
    dependent: :destroy

end

component_controller.rb:

  before_action :load_project
  before_action :load_scope  

  def index
    components = paginate @scope, per_page: per_page
    data = ActiveModelSerializers::SerializableResource.new(
      components,
      each_serializer: ComponentSerializer
    )
    render_response(:ok, { data: data })
  rescue ActiveRecord::RecordNotFound
    render_response(:not_found, { resource: "Project/Lesson" })
  end

  def load_scope
    @scope = @project.components
    @scope = @scope.order("position")
  end

  def load_project
    @project = Project.find(params[:project_id])
  rescue ActiveRecord::RecordNotFound
    render_response(:not_found, { resource: "Project/Lesson" })
  end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...