【问题标题】:Passing argument to grape-entity modules将参数传递给葡萄实体模块
【发布时间】:2014-12-11 16:52:30
【问题描述】:

我的项目要求现在迫使我将参数传递给嵌套实体。 我有一个实体 A 和一个实体 B,它们显示了一些信息,并且需要系统上的 A 标识符来构建它们。

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

在上面的例子中,我想做这样的事情:

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

并且在嵌套实体中使用trip_id参数选项是这样的:

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

但是说对象没有被定义到实体中是失败的。有没有办法做到这一点? 有什么想法吗?

【问题讨论】:

  • 我不确定,但我认为在这种情况下您无权访问父对象。此外,“公开”方法不会将额外参数传递给“选项”哈希,因此您不能那样做。但请注意,您可以使用“present”方法将额外参数传递给 API 中的“options”哈希,因此您可以使用这种方法来传递父对象。但是,我认为它在您返回数组的情况下不起作用。
  • 我正在使用当前行程,:with => Trips::TripResponseEntity 用于通过一行代码呈现一个集合,并且这种方法禁止我使用额外的参数。
  • 不,Grape 允许您执行类似“当前行程,:with => Trips::TripResponseEntity, :trip => trip”的操作。在您的 Trip 或 Destination 实体中,您可以使用“options[:trip]”访问此参数。
  • 想象一下如何使用模型中的方法来做到这一点?这意味着,离开响应实体方式。在旅行中:暴露 all_destinations 并且模型有一个名为 all_destinations 的方法,当目的地 json 像响应实体一样被格式化时。此时我有了trip_id。

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 grape grape-entity


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多