【问题标题】:Grape API gem: How to display associated Models as nested JSONGrape API gem:如何将关联模型显示为嵌套 JSON
【发布时间】:2013-11-05 21:56:54
【问题描述】:

我目前正在构建一个 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

可以肯定地假设所有者拥有许多博客,而所有者又拥有许多帖子。

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

【问题讨论】:

  • 你需要问一个实际的问题——它可能有助于解释你得到的结果(所以我不必启动你的代码来检查)。我假设输出不是您所期望的 - 我认为这将输出博客列表,因为运行的最后一个 present 是最外面的一个将输出 owner.blogs。您是否尝试过使用grape-entity

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


【解决方案1】:

也许你会发现葡萄实体宝石有用:https://github.com/intridea/grape-entity

你可以为你的模型定义一个“嵌套实体”:

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
# ...

我希望这会有所帮助。

【讨论】:

  • 我认为值得注意的是,OP 中使用的 present 方法不会“建立”多个调用(因为看起来 OP 正在尝试这样做),而只是设置路线的输出。您的答案通过grape-entity 在一个方法调用中提供了嵌套结构,也可以有一个方法Owner.blogs_structure 通过直接遍历模型属性返回一个深度哈希数组。基本上grape-entity 添加了一个很好的声明性语法来做到这一点。
猜你喜欢
  • 1970-01-01
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
相关资源
最近更新 更多