【问题标题】:grape-entity represent not working葡萄实体代表不工作
【发布时间】:2015-06-02 05:43:30
【问题描述】:

我使用grape gem 为APIgrape-entity 生成响应。

简单的show/get 请求响应良好,就像只返回来自ActiveRecord Object 的数据一样。 很好

当我尝试包含来自has_many 关系的数据时,它会返回与该对象相关的所有数据。 很好

但是当我represent数据喜欢

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

根据documentation,它应该返回类似这样的内容:

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

但是它会返回:

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

我的PostEntities 包含:

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

我的CommentEntities 包含:

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

represent 方法有问题。我不明白问题是什么?

【问题讨论】:

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


    【解决方案1】:

    查看葡萄CHANGELOG,你会发现represent函数将在下一个版本(0.4.6)中使用。

    0.4.6(下一个)#114:添加了“仅”选项,用于选择应返回的属性 - @estevaoam。

    所以,如果你现在想使用这个功能,你可以使用最新的github版本。

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

    【讨论】:

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