grape-entity represent not working

1.6k Views Asked by At

I am using grape gem for API and grape-entity to generate responses.

Simple show/get request is responding fine like returning only data from ActiveRecord Object. Fine

When i try to include data from has_many relation it return all the data related to that object. Fine

But when I represent data like

post = Post.first
data = V1::Entities::PostEntities.represent(post, only: [:id, { comments: [:id, :body] }])
data.as_json

It should return something like this as per documentation:

{
  id: 1,
  comments: [{
    id: 1,
    body: 'example'
  }]
}

But it returns:

{
  id: 1,
  comments: [{
    id: 1,
    user_id: 1,
    body: 'example',
    created_at: 'some_timestamp',
    updated_at: 'also_some_timestamp',
    is_deleted: 0,
  }]
}

My PostEntities contains:

module V1
  module Entities
    class PostEntities < Grape::Entity
      expose :id
      expose :comments, with: V1::Entities::CommentEntities
    end
  end
end

My CommentEntities contains:

module V1
  module Entities
    class CommentEntities < Grape::Entity
      expose :id
      expose :user_id
      expose :body
      expose :created_at
      expose :updated_at
      expose :is_deleted
    end
  end
end

there is something wrong with represent method. i am not getting what the issue is?

1

There are 1 best solutions below

0
On

Check out the grape CHANGELOG, and you will find out that the represent function will work in next version(0.4.6).

0.4.6 (Next) #114: Added 'only' option that selects which attributes should be returned - @estevaoam.

So, if you want to use this function right now, you can use the newest github version.

gem 'grape-entity', github: "intridea/grape-entity", branch: "master"