Big*_*ird 1 ruby api json ruby-on-rails ruby-grape
我目前正在构建一个 API 来访问特定所有者的博客上的所有帖子。我想在博客模型下将它们显示为嵌套的 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
Run Code Online (Sandbox Code Playgroud)
可以安全地假设所有者拥有许多博客,进而拥有许多帖子。
也许你会发现葡萄实体宝石很有用: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
Run Code Online (Sandbox Code Playgroud)
然后,在端点中:
# ...
present owner.blogs, with: YourApp::Entities::Blog
# ...
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助。
| 归档时间: |
|
| 查看次数: |
3355 次 |
| 最近记录: |