null
null

Reputation: 9114

How to get enum value from its index in ruby-on-rails?

For example I have this enum in ruby-on-rails:

class Foo < ActiveRecord::Base enum color: [ :red, :green, :blue ] end

By default, the index should be :red -> 0, :green -> 1, and so on.

I want to get the enum value by index, let's say from index 1, so the result should be :green. Is it possible to do this ?

Update:

Pseudo-code example:

Foo.colors.find_by_index(1) # returns :green

Upvotes: 1

Views: 4226

Answers (2)

lg86
lg86

Reputation: 375

You can try these

class Fooo < ActiveRecord::Base
  enum colo: {red: 0, green: 1, blue: 2}
end

Upvotes: 0

mgidea
mgidea

Reputation: 494

Foo.colors returns a hash:

{:red => 0, :green => 1, :blue => 2}

You can invert the hash to get the indexed value

Foo.colors.invert
# {0 => :red, 1 => :green, 2 => :blue}

Upvotes: 2

Related Questions