【问题标题】:User Grape Entity with Arrays带有数组的用户葡萄实体
【发布时间】:2016-05-25 14:18:23
【问题描述】:

我想知道 Grape Entity 是否可以用于渲染哈希数组,我想我记得它有效,但不知何故我现在无法让它工作,我是否犯了一些明显的错误?这是我的实体:

class V1::Entities::Searchresult < Grape::Entity
   expose :_type, as: :type
   expose :_id, as: :id
   expose :_score, as: :score
   expose :highlight
end

在我的 API 中,我这样调用渲染:

present result['hits']['hits'], with: V1::Entities::Searchresult, :params => params

'result['hits']['hits']' 填充了 10 个包含数据的哈希值。数据存在。但是,当我查看结果时,我得到:

[
  {
    "type": null,
    "id": null,
    "score": null,
    "highlight": null
  },
  {
    "type": null,
    "id": null,
    "score": null,
    "highlight": null
  },
  ......

我做错了什么,或者这根本不可能。我似乎无法挖掘有关数组主题的任何文档。

干杯

汤姆

【问题讨论】:

    标签: ruby-on-rails grape-api grape-entity


    【解决方案1】:

    我发现了错误,Grape::Entity::Delegator::HashObject 无法使用具有字符串键而不是符号的散列。它无法提取值。

      data = []
      result['hits']['hits'].each do |item|
        data << item.symbolize_keys
      end
    
      present data, with: V1::Entities::Searchresult, :params => params
    

    此解决方法忽略了该问题。我还将打开一个 github 问题进行修复,因为一个简单的

    object[attribute] || object[attribute.to_s]
    

    会解决整个问题,而不是只使用

    object[attribute]
    

    读取属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多