grape-entity icon indicating copy to clipboard operation
grape-entity copied to clipboard

Exposing a List of Entities

Open Linell opened this issue 10 years ago • 2 comments
trafficstars

So I have an Employee entity that looks something like this.

class Employee::Entity < Grape::Entity
  expose :id, :name, :company
end

The Employee has tons of clock ins to the timecard system. The entity for a Clockin is something like:

class Clockin::Entity < Grape::Entity
  expose :id, :year, :date, :code, :description
end

Displaying all of the clock ins for an employee is easy enough. How would I go about segregating them by year, though?

My first thought was adding something like this to the Employee entity

expose :clockins do |employee, options|
  employee.clockins.group_by { |c| c[:year] }
end

That does get the correct data, but it's not presented correctly.

Linell avatar Oct 26 '15 19:10 Linell

Define doesn't get presented correctly? The structure returned from a group_by is a hash, so you should use a new presenter for it that knows how to deal with it?

dblock avatar Oct 26 '15 19:10 dblock

Instead of exposing only the items explicitly exposed in the Clockin entity, I get the entire object.

I've actually tried it this way as well,

expose :clockins, :using => Clockin::Entity do |employee, options|
  employee.clockins.group_by { |c| c[:year] }
end

, which just results in an object full of null values.

Linell avatar Oct 26 '15 19:10 Linell