2012-04-26 32 views
1

我有這個樣本文檔:如何Mongoid迴歸模型的字段中使用Rails和JSON

{ 
    "_id" : ObjectId("4f98fd1df2699a2f8a000003"), 
    "comments" : "Foo bar", 
    "location" : "Somewhere", 
    "user_id" : ObjectId("4f98fd1df2699a2f8a000001") 
} 

當我使用控制器獲取的數據:

respond_to :json 

def index 
    respond_with Comment.all 
end 

它返回JSON:

[{ 
    "_id": "4f98fd1df2699a2f8a000003", 
    "comments": "Foo bar", 
    "location": "Somewhere", 
    "user_id": "4f98fd1df2699a2f8a000001", 
}] 

我的問題是如何輕鬆地在響應中包含User類的字段?

class User 
    include Mongoid::Document 

    field :username 
    field :first_name 
    field :last_name 
end 

回答

2

你需要重寫的as_json默認值。

def index 
    respond_with Comment.all.as_json(:include => "user") 
end 

更好的選擇是使用JSON模板構建器,如Jbuilder

+0

謝謝!有效! :-) – Ben 2012-04-26 12:56:01

0

與嘗試:

respond_with Comment.includes(:user).all 

See the doc here.

+0

感謝您的迴應。仍然得到相同的JSON響應。我試圖將identity_map_enabled:true包含到mongoid.yml中並重新啓動服務器。沒有運氣。我是否需要向模型類添加內容? – Ben 2012-04-26 10:17:11

相關問題