0

当我执行 Object.to_json 时,Mongoid 不会将子文档包含到 JSON 中。我该怎么做?我试过这个:

@realty = Realty.includes(:comments).find(params[:id])
...
respond_to do |format|
  format.json  { render json: @realty }
end

但是评论仍然没有包含在 JSON 中。

4

2 回答 2

2

您需要在 to_json 调用中使用 :include

@realty = Realty.find(params[:id])
...
respond_to do |format|
  format.json  { render json: @realty.to_json(include: [:comments]) }
end

您可以在其中包含任何关联。

您还可以使用任何随机方法:

@foo.to_json(methods: [:some_arbitrary_method])

这适用于较小/简单的 api,但请查看:
JBuilder,它是 Rails 4 默认 gem 包含的一部分,显然您可以将其与任何 Rails 版本的
ActiveModel 序列化程序一起使用

于 2013-07-05T13:24:49.410 回答
0

我只是在做这样的事情,我使用:

gem "active_model_serializers"

https://github.com/rails-api/active_model_serializers

http://railscasts.com/episodes/409-active-model-serializers

在我的情况下Project has_many :posts,json结果将是:

{"projects":[{"id":1,"title":"test project","description":"nice test project","slug":null,"posts":[{"id":1,"title":"new test post for test project","body":"Some content here and there","responses":[],"author":{"id":1,"email":"admin@mail.md"}}],"members":[]}]}

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :title, :description, :slug
  has_many :posts
  has_many :memberships, key: :members
end

class PostSerializer < ActiveModel::Serializer
  attributes :id, :title, :body, :responses
end
于 2013-07-05T10:55:15.573 回答