如何使用 jsonapi-resources ruby gem 重命名资源 property/attribute

How to rename property/attribute of resource with jsonapi-resources ruby gem

我正在用 rails 使用 jsonapi-resources gem 构建 json api。图书馆真的很棒,它做了很多工作。

然而,我们数据库中的某些列名称在 API 中显示并不是真正有意义的。

那么,我的问题是:可以在资源中重命名 property/attribute 吗?

示例:

假设我有属性为 login 的模型用户。

class User < ActiveRecord::Base
  attr_accessor :login
end

我希望 API 中的 login 显示为 username,例如:

class UserResource < JSONAPI::Resource
  attribute :username, map_to: :login
end

谢谢!

我认为您需要使用别名或 alias_method。 http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

通常,更改属性名称或值的最简单方法是 re-define 属性。在你的情况下它将是:

attributes :username

def username
  @model.login
end

在自述文件中:https://github.com/cerebris/jsonapi-resources#formatting

为您的 :login 属性设置 :username alias

class User < ActiveRecord::Base
  attr_accessor :login

  alias_attribute :username, :login
end

然后在 JSONAPI::Resources (JR) 中,您可以像这样指定 username 属性:

class UserResource < JSONAPI::Resource
  attribute :username
end

通过设置别名,您已将 username 属性映射到 login 属性,因此无论您使用 username 还是 login 都没有关系, 它将 return 相同的值。