【发布时间】:2018-03-15 01:09:18
【问题描述】:
我正在尝试使用以下 JSON 结构构建 Rails API:
{ team: "team_name",
players: players: [
{
name: "player_one",
contracts: [
{
start_date: '7/1/2017',
seasons: [
{
year: 2017,
salary: 1000000
}
]
}
]
},
{
name: "player_two"
}
]
}
我的模型设置如下:
class Team < ApplicationRecord
has_many :players
end
class Player < ApplicationRecord
belongs_to :team
has_many :contracts
end
class Contract < ApplicationRecord
belongs_to :player
has_many :seasons
end
class Season < ApplicationRecord
belongs_to :contract
end
我目前正在使用以下代码,但我想使用 ActiveModel 序列化器(或其他干净的解决方案)清理它
def show
@team = Team.find(params[:id])
render json: @team.as_json(
except: [:id, :created_at, :updated_at],
include: {
players: {
except: [:created_at, :updated_at, :team_id],
include: {
contracts: {
except: [:id, :created_at, :updated_at, :player_id],
include: {
seasons: {
except: [:id, :contract_id, :created_at, :updated_at]
}
}
}
}
}
}
)
end
此外,数组项按 ID 降序显示,我希望将其反转。我也希望通过第一份合同、第一个赛季、薪水来订购球员。
【问题讨论】:
标签: ruby-on-rails active-model-serializers