【问题标题】:Accept string input for attribute, store integer in DB, return string in API接受属性的字符串输入,将整数存储在数据库中,在 API 中返回字符串
【发布时间】:2019-08-10 19:27:44
【问题描述】:

我正在构建一个 rails api 应用程序。我有一个动物课

class Animal < ActiveRecord::Base
  TYPES = { herbivore: 1, carnivore: 2, omnivore: 3 }
  attr_reader :name, :type
end

在 DB 中,我将类型的值保存为整数 1、2、3。

在控制器中,创建操作接受类型为“herbivore”、“carnivore”或“omnivore”

#POST animals
Request:  { name: "tommy", type: "carnivore" }
Response: { id: 1 }, status: 204

同样,show action 以“herbivore”、“carnivore”或“omnivore”响应

#GET animals/1
Response: { id: 1, name: "tommy", type: "carnivore" }, status: 200

为了实现我想要的,我在我的 Animal 类中添加了这些方法

def type=(value)
 super(TYPES[value.to_sym])
end

def type
  TYPES.key(read_attribute(:type))
end

这很好用。

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rails-api


    【解决方案1】:

    你可以使用ActiveRecord::Enum,像这样:

    class Animal < ActiveRecord::Base
      enum type: [ :herbivore, :carnivore, :omnivore ]
    end
    

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 2018-07-29
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多