ChimpWithaKeyboard
ChimpWithaKeyboard

Reputation: 43

Accept string input for attribute, store integer in DB, return string in API

I am building a rails api app. I have an Animal class

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

In DB, I am saving the values for type as integers 1, 2, 3.

In the controller, the create action accepts type as "herbivore", "carnivore" or "omnivore"

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

Similarly, the show action responds with "herbivore", "carnivore" or "omnivore"

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

To achieve what I want, I have added these methods in my Animal class

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

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

And this works fine.

Is there a better way to do this?

Upvotes: 3

Views: 78

Answers (1)

ArtuX
ArtuX

Reputation: 374

You can use ActiveRecord::Enum, like this:

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

Upvotes: 3

Related Questions