2011-08-17 60 views
0

現在在我的線程控制器我有以下如何建立一個JSON對象

def thread 
    @thread = Thread.find(params[:id]) 
    .... 
    render :json => {"success" => 1}, :content_type => 'application/json' 
end 

我想什麼做的是建立JSON響應包括@thread,但只有一些PARAMS所以它的東西像這樣:

{"success" => 1, "thread" => {"id": 1, "title": "hello world"} 

任何想法如何在軌道控制器中構建這個json對象?目標是不包括所有線程字段幷包含不是線程字段的成功?

感謝

回答

3

你應該使用模型的as_json功能。

render :json => {"success" => 1, :thread => @thread.as_json(:only => [:my, :wanted, :attributes]) } 

as_json包括大量的選項,以幫助您構建準備JSON編碼包括only,並且except其中將包括對模型的所有屬性除了列出的哈希值。 methods它將添加對象上的其他可用方法和include以將關聯(belongs_to,has_one,has_many等)添加到哈希中。

欲瞭解更多信息,請參閱as_json文檔:http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

1

如何

render :json => {"success" => 1, "thread" => { "id" => @thread.id, "title" => @thread.title } }, :content_type => 'application/json' 
1
render :json => {"success" => 1, "thread" => @thread.attributes.select{ |k, v| ["id", "title"].include? k }} 
相關問題