2012-02-19 28 views
1

我在我的rails應用程序中使用acts_as_taggable_on。我希望這些標籤顯示在我模型的to_json表示中。在模型的to_json輸出中包含acts_as_taggable_on標記

例如,我的模型的一個實例的to_json看起來是這樣的:

{"created_at":"2012-02-19T03:28:26Z", 
"description":"Please!", 
"id":7, 
"points":50, 
"title":"Retweet this message to your 500+ followers", 
"updated_at":"2012-02-19T03:28:26Z"} 

...我想它是這個樣子:

{"created_at":"2012-02-19T03:28:26Z", 
"description":"Please!", 
"id":7, 
"points":50, 
"title":"Retweet this message to your 500+ followers", 
"updated_at":"2012-02-19T03:28:26Z" 
"tags" : 
    {"id":1, 
     "name":"retweet"}, 
    {"id":2, 
     "name":"twitter"}, 
    {"id":3, 
     "name":"social"} 
} 

我的控制器代碼只是腳手架給我的默認設置:

def show 
    @favor = Favor.find(params[:id]) 

    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render json: @favor } 
    end 
end 

請注意,我已經可以訪問模板中的@ favor.tags,並且@ favor.tags.to_json按預期工作,我只是在輸出@ favor.to_json時需要包含這些數據。

回答

3

您可以通過調用to_json將選項傳遞給json調用。或者通過在你喜歡的模型中重新定義as_json

render json: @favor.to_json(include: :tags)

2

在您的青睞模型覆蓋as_json方法。

def as_json(options={}) 
    super(:include => :tags) 
end 
相關問題