3

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?

1 Answer 1

3

You can use ActiveRecord::Enum, like this:

class Animal < ActiveRecord::Base
  enum type: [ :herbivore, :carnivore, :omnivore ]
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.