当我执行Object.to_json时,Mongoid不会将子文档包含到JSON中。我该怎么做?我试过这个:
@realty = Realty.includes(:comments).find(params[:id])
...
respond_to do |format|
format.json { render json: @realty }
end
但是评论仍未包含在JSON中。
答案 0 :(得分: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 Serializers
答案 1 :(得分: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