Grape API gem:如何将关联模型显示为嵌套JSON

时间:2013-11-05 21:56:55

标签: ruby-on-rails ruby json api grape

我目前正在构建一个API来访问博客上针对特定所有者的所有帖子。 我想在Blog模型下将它们显示为嵌套的json。

class API < Grape::API
format :json
prefix "api"
resource "posts" do
  get ':id' do
    owner = Owner.find(params[:id])
    present owner.blogs.each do |b|
        present b
        b.posts.each do  |p|
            present p
        end
    end
  end
end
end

可以安全地假设所有者拥有许多博客&amp;反过来有很多帖子。

源: https://github.com/intridea/grape

1 个答案:

答案 0 :(得分:3)

也许你可以找到有用的葡萄实体宝石:https://github.com/intridea/grape-entity

通过它你可以定义一个&#34;嵌套实体&#34;适合您的型号:

module YourApp
  module Entities
    class Blog < Grape::Entity
      expose :id, :blog_title
      expose :posts, using: YourApp::Entities::Post
    end

    class Post < Grape::Entity
      expose :id, :post_title
    end
  end
end

而且,在端点中:

# ...
present owner.blogs, with: YourApp::Entities::Blog
# ...

我希望这会有所帮助。