【发布时间】: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