1

我有这个示例文档:

{
    "_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
4

2 回答 2

2

您需要覆盖as_json.

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

更好的选择是使用 JSON 模板构建器,例如Jbuilder

于 2012-04-26T10:59:55.417 回答
0

试试看:

respond_with Comment.includes(:user).all

请参阅此处的文档。

于 2012-04-26T09:42:34.630 回答