gpt4 book ai didi

ruby-on-rails - 向 Grape 实体添加常量属性

转载 作者:行者123 更新时间:2023-12-04 00:32:38 24 4
gpt4 key购买 nike

我正在尝试使用 Rails 和 Grape 构建一组 API。用户模型如下:

{
"email": "foo@bar.com"
"name": "Foo Bar"
}

现在,在 API 表示级别,我希望用户对象如下所示:

{
"object": "User"
"email": "foo@bar.com"
"name": "Foo Bar"
}

由于我使用 Grape Entity gem 来公开我的模型,因此真正的问题是:How to add an extra CONSTANT-value attribute to a Grape Entity class? 感谢您的帮助!

最佳答案

您可以通过向类添加一个函数来添加一个额外的字段,如下所示:

class XXX < Grape::Entity
expose :object_name
expose :email
expose :name

private
def object_name
"User"
end
end

但是如果函数的名字是object,就不行了。您已为此字段选择了另一个名称。

对于更多选项,您还可以使用这样的 block ,在这种情况下,无论您使用的是什么字段名称。

class XXX < Grape::Entity
expose :object do |you_have_to_set_a_parameter_here|
"User"
end
expose :email
expose :name
end

关于ruby-on-rails - 向 Grape 实体添加常量属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27520432/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com