Reputation: 427
I'm currently building a API to access all posts on a blog for a specific owner. I'd like to display them as nested json under the Blog model.
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
It's safe to assume that a Owner has many blogs & in turn has many posts.
source: https://github.com/intridea/grape
Upvotes: 1
Views: 3613
Reputation: 548
Maybe you could find useful the grape-entity gem: https://github.com/intridea/grape-entity
With that you can define a "nested entity" for your model:
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
And than, in the endpoint:
# ...
present owner.blogs, with: YourApp::Entities::Blog
# ...
I hope this helps.
Upvotes: 5