3

The requirements of my project are now forcing me to passing parameters to nested entities. I have an entity A and an entity B that show some information and needs the A identifier on the system to build them.

module Services
 module Trips
  class TripPreviewResponseEntity < Grape::Entity
   expose :id
   expose :title
   expose :duration
   expose :total_price
   expose :description
   expose :details
   expose :destinations, using: Destinations::DestinationResponseEntity
  end
 end
end

In the example above I want to do something like that:

expose :destinations, using: Destinations::DestinationResponseEntity, :trip_id => object.id

And in the nested Entity use the trip_id parameter option in this way:

expose :trip_info do |item,options|
   item.show(options[:trip_id])
end

But it's failing saying that object is not defined into the entity. Is there a way to perform this? Any idea?

halbano
  • 1,135
  • 14
  • 34
  • I'm not sure but I think that you don't have access to the parent object in this case. Furthermore, the "expose" method doesn't pass the extra parameters to the "options" hash so you can't do it that way. But notice that you can pass extra parameters to the "options" hash in your API using the "present" method so you can use this approach to pass your parent object. However, I think it won't work in the cases where you're returning arrays. – Marlon Dec 13 '14 at 00:25
  • I'm using present trips, :with => Trips::TripResponseEntity for present a collection with one line of code and this approach id forbidding me to use an extra parameter. – halbano Dec 14 '14 at 00:03
  • No, Grape allow you to do something like this "present trip, :with => Trips::TripResponseEntity, :trip => trip". Inside your Trip or Destination entity you can access this parameter using "options[:trip]". – Marlon Dec 14 '14 at 00:18
  • Do imagine how to do it using methods inside the models? It means, leaving outside the Response Entity way. In trip: expose all_destinations and the model have a method called all_destinations when the destinations json are formatted like the response entity was doing. At this point I have the trip_id. – halbano Dec 15 '14 at 18:02

1 Answers1

3
module Services
 module Trips
  class TripPreviewResponseEntity < Grape::Entity
   expose :id
   expose :title
   expose :duration
   expose :total_price
   expose :description
   expose :details
   expose :destinations do |trip, _options| 
     DestinationResponseEntity.represent(trip.destinations, trip_id: trip.id)
   end
  end
 end
end
Oshan Wisumperuma
  • 1,808
  • 1
  • 18
  • 32