Как мне сериализовать отношения habtm в Ruby on Rails с fast_jsonapi - PullRequest
0 голосов
/ 13 ноября 2018

Я создал приложение Ruby on Rails API, в котором я хотел реализовать JSON API с fast_jsonapi .Сейчас я борюсь с отношениями, которые не показаны.Что мне нужно изменить?

Это моя схема.db:

create_table "candidates", force: :cascade do |t|
  t.string "place"
  t.string "zip_code"
  t.string "address"
  t.string "date_of_birth"
  t.string "title"
  t.string "profile_picture"
  t.string "first_name"
  t.string "last_name"
  t.string "email_address"
  t.boolean "confirm_terms_and_conditions"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

create_table "candidates_degrees", id: false, force: :cascade do |t|
  t.bigint "candidate_id"
  t.bigint "degree_id"
  t.index ["candidate_id"], name: "index_candidates_degrees_on_candidate_id"
  t.index ["degree_id"], name: "index_candidates_degrees_on_degree_id"
end

create_table "degrees", force: :cascade do |t|
  t.string "degree"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

А это мои модели:

class Candidate < ApplicationRecord
  has_and_belongs_to_many :degrees, dependent: :nullify
end

class Degree < ApplicationRecord
  has_and_belongs_to_many :candidates, dependent: :nullify
end

Это мои сериализаторы:

class CandidateSerializer
  include FastJsonapi::ObjectSerializer
  attributes :place, :zip_code, ...
  has_many :degrees
end

class DegreeSerializer
  include FastJsonapi::ObjectSerializer
  attributes :degree
  has_many :candidates
end

1 Ответ

0 голосов
/ 14 ноября 2018

вам нужно внести изменения в CandidateSerializer и DegreeSerializer.

Вместо записи отдельного отношения HABTM в сериализаторе вы можете прямо в attributes

1008 * например *

class CandidateSerializer
  include FastJsonapi::ObjectSerializer
  attributes :place, :zip_code,:degrees
end

ответ

{
  :data=>
    {:id=>"",
     :type=>:candidate,
     :attributes=> {   
       degrees: {}
     }
 }

то же самое для DegreeSerializer

  class DegreeSerializer
    include FastJsonapi::ObjectSerializer
    attributes :candidates
  end
...