[英]Rails Rabl - Custom array keys
我正在嘗試自定義我的 RABL API 響應。 我有一個游戲集合,每個游戲都包含多個玩家。 現在我的玩家存儲在一個數組中,但我需要通過一個鍵來訪問它們,所以我想自定義我的 json 響應。
這是我的base.rabl
文件:
collection @games
attributes :id
child(:players) do |a|
attributes :id, :position
end
這就是我得到的:
[
{
id: 1,
players: [
{
id: 27,
position: 'goalkeeper'
},
{
id: 32,
position: 'striker'
},
{
id: 45,
position: 'defender'
}
]
}
]
這就是我想要得到的:
[
{
id: 1,
goalkeeper: {
id: 27
},
striker: {
id: 32
},
defender: {
id: 45
}
}
]
目前我找不到一種方法來顯示除一系列對象之外的玩家。
有人可以給我一個打擊嗎? 我嘗試了很多 rabl 配置,但目前沒有成功......
編輯:
我更改了屬性,使其更加明確。 每場比賽都有許多玩家,每個玩家都有不同的位置。
為了添加更多細節以便您了解我想要實現的目標,這是我的最佳嘗試:
base.rabl 文件:
object @games
@games.each do |game|
node(:id) { |_| game.id }
game.players.each do |player|
if (player.position == 'goalkeeper')
node(:goalkeeper) { |_| player.id }
elsif (player.position == 'striker')
node(:striker) { |_| player.id }
end
end
end
這就是我得到的:
[
{
id: 1,
goalkeeper: {
id: 27
},
striker: {
id: 32
}
},
{
id: 1,
goalkeeper: {
id: 27
},
striker: {
id: 32
}
}
]
結構是我想要的,但是每個返回的游戲都是相同的。 如果我的查詢結果包含 4 個游戲,它會返回 4 個游戲,但它們都是相同的...
如果你有模型...
class Game < ActiveRecord::Base
has_many :players
end
class Player < ActiveRecord::Base
belongs_to :game
end
在您的base.json.rabl
文件中,您可以執行以下操作:
attributes :id
node do |game|
game.players.each do |player|
node(player.position) { { id: player.id } } # I suggest node(pos) { player.id }
end
end
在你的index.json.rabl
你需要有:
collection @games
extends 'api/games/base' # the base.rabl path
在你的show.json.rabl
你需要有:
object @game
extends 'api/games/base' # the base.rabl path
在您的GamesController
您需要執行以下操作:
respond_to :json
def index
@games = Game.all
respond_with @games
end
def show
@game = Game.find(params[:id)
respond_with @game
end
所以,如果你的請求是GET /api/games
你會點擊index.json.rabl
並且你會得到你想要的響應。
如果你只想看一場比賽,你需要點擊GET /api/games/:id
- 我假設你有一個命名空間
api
。 我不知道GET /api/games
真的存在,但是你明白了。- 我假設你在一場比賽中每個球員都有一個位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.