如何在Rails中将嵌套模型作为JSON返回

时间:2014-09-14 13:25:40

标签: ruby-on-rails json rest

class User < ActiveRecord::Base
  has_many :images
end
class Image < ActiveRecord::Base
  has_many :sub_images
  belongs_to :user
end
class SubImage < ActiveRecord::Base
  belongs_to :image
end

路线

/users/:user_id
/users/:user_id/images/:image_id
/users/:user_id/images/:image_id/subimages/:subimage_id

resources :users do
  resources :images, :controller => "Images" do
    resources :subimages, :controller => "SubImages" do
    end
  end
end

目标:当我向用户1发出请求时,它应该返回所有用户1图像和嵌套的子图像。

目前,代码仅返回用户1张图片。我希望它也能返回子图像。

1 个答案:

答案 0 :(得分:2)

使用Rails API ActiveModel Serializers。您需要为模型创建Serializer类,并在JSON输出中指定所需的属性。

您可以为现有模型生成序列化程序:

rails g serializer post

给出帖子和评论模型:

class PostSerializer < ActiveModel::Serializer
  attributes :title, :body

  has_many :comments

  url :post
end

class CommentSerializer < ActiveModel::Serializer
  attributes :name, :body

  belongs_to :post_id

  url [:post, :comment]
end

默认情况下,序列化帖子时,您也会获得其评论。

现在,在您的控制器中,当您使用render:json时,Rails现在将首先搜索该对象的序列化程序并在可用时使用它。

class PostsController < ApplicationController
  def show
    @post = Post.find(params[:id])

    render json: @post
  end
end

在这种情况下,Rails将查找名为PostSerializer的序列化程序,如果存在,则使用它来序列化Post。