Ruby on rails 接受属性的字符串输入,在DB中存储整数,在API中返回字符串
我正在构建一个rails api应用程序。我有一门动物课Ruby on rails 接受属性的字符串输入,在DB中存储整数,在API中返回字符串,ruby-on-rails,ruby,activerecord,rails-api,Ruby On Rails,Ruby,Activerecord,Rails Api,我正在构建一个rails api应用程序。我有一门动物课 class Animal < ActiveRecord::Base TYPES = { herbivore: 1, carnivore: 2, omnivore: 3 } attr_reader :name, :type end 同样,表演动作的反应是“食草动物”、“食肉动物”或“杂食动物” 为了实现我想要的,我在我的动物类中添加了这些方法 def type=(value) super(TYPES[value.to_sy
class Animal < ActiveRecord::Base
TYPES = { herbivore: 1, carnivore: 2, omnivore: 3 }
attr_reader :name, :type
end
同样,表演动作的反应是“食草动物”、“食肉动物”或“杂食动物”
为了实现我想要的,我在我的动物类中添加了这些方法
def type=(value)
super(TYPES[value.to_sym])
end
def type
TYPES.key(read_attribute(:type))
end
这个很好用
有更好的方法吗?您可以这样使用:
class Animal
#GET animals/1
Response: { id: 1, name: "tommy", type: "carnivore" }, status: 200
def type=(value)
super(TYPES[value.to_sym])
end
def type
TYPES.key(read_attribute(:type))
end