2016-02-25 40 views
0

我正在構建一個使用Ruby on Rails和Angular前端與此後端交互的REST API。使用寶石rails-api。因此,我只在我的請求中使用json數據,不使用html。見json:關鍵字:Rails REST API - 返回任何嵌套對象的ID而不是對象本身

def show 
    @article = Article.find(params[:id]) 
    render json: @article 
end 

比方說,我有2種型號:

  • 音樂
  • 文章:可能包含音樂belongs_to :music

在之前的snipp中代碼等,一文章資源回報這種JSON的一個GET(簡體):

{ 
    "id":2, 
    "title":"A great title", 
    "content":"The amazing content of my article", 
    "music":{ 
    "id":8, 
    "artist":"Pink Floyd", 
    "title":"Wish You Were Here" 
    } 
} 

它返回包含到對象的對象音樂。這是Ruby on Rails的默認行爲。但我總是聽說適當的REST API應該返回嵌套資源的位置而不是資源本身。我想通過返回文章中出現的音樂的ID來遵循這條黃金法則。

我要的是回到音樂,而不是整個對象的ID,所以JSON響應應該是這樣的:

{ 
    "id":2, 
    "title":"A great title", 
    "content":"The amazing content of my article", 
    "music":8 
} 

我期待的文檔的選項中找到添加某處爲了激活這個行爲,或者至少一個關於自制解決方案的帖子,但我沒有。我很驚訝這個簡單但重要的東西(至少對我來說)沒有實現。

您的幫助將不勝感激!

回答

0

我正在查找的行爲由Serializer處理。因此,解決方案是在我不想要的音樂對象相應的串行指定:

class ArticleSerializer < ActiveModel::Serializer 
    attributes :id, :title, :content, :created_at, :music 
end 

但音樂對象的ID(:music_id):

class ArticleSerializer < ActiveModel::Serializer 
    attributes :id, :title, :content, :created_at, :music_id 
end 
相關問題