我创建了一个Rails应用程序,我想用佐纳皮实现一个JSON。现在我在为那些没有显示出来的关系而挣扎。我要换什么?
这是我的schema.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发布于 2018-11-14 10:54:08
您需要对CandidateSerializer和DegreeSerializer进行更改。
与在序列化器中写入单独的HABTM关系不同,您可以直接在attributes中编写
e.g
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发布于 2020-10-06 19:49:42
你可以这样做:
class CandidateSerializer
include FastJsonapi::ObjectSerializer
attributes :place, :zip_code,...
has_many :degrees, if: Proc.new { |record| record.association(:dregrees).loaded? }
endclass DegreeSerializer
include FastJsonapi::ObjectSerializer
has_many :candidates, if: Proc.new { |record| record.association(:candidates).loaded? }
end在您的API操作中(例如,在这里使用显示路由):
def show
@candidate.degrees.load
render json: CandidateSerializer.new(@candidate, options).serialized_json if stale?(@candidate)
end
private
def set_candidate
@candidate = Candidate.find_by(id: params[:id])
end
def options
{ include: [:degrees] }
end结果
{
"data": {
"id": "20",
"type": "candidate",
"attributes": {
"id": 20,
...
},
"relationships": {
"degrees": {
"data": [
{
"id": "713",
"type": "degree"
}
]
}
}
},
"included": [
{
"id": "713",
"type": "degree",
"attributes": {
"id": 713,
...
},
"relationships": {}
}
]
}https://stackoverflow.com/questions/53287872
复制相似问题