1

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

8
  • Why don't you define an array instead of enum ? Commented Jan 7, 2018 at 21:16
  • What if you have two columns with enums? How do you expect rails to work in that case? Commented Jan 7, 2018 at 21:18
  • Send me some sample code including your expected output. Commented Jan 7, 2018 at 21:19
  • I also use the enum for Formtastic's select input (e.g. f.input :color, as: :select, collection: Foo.colors). The enum index would be the option value, and the enum value itself as the display text/label. Array doesn't fit for this case I think. Another way is using Hash, but here I would like to know if it's possible to get enum value by index. Commented Jan 7, 2018 at 21:41
  • 1
    Okay well you could do as Foo.colors.keys(1) #=> "green" becuase colors is simply a HashWithIndifferentAccess so it acts very similar to a Hash but all the Symbol keys are going to be Strings. Commented Jan 8, 2018 at 19:10

2 Answers 2

2

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}
Sign up to request clarification or add additional context in comments.

1 Comment

Great way to use enums when the value of the is a number. I used it like that: Products.categories.invert[@product.categories] and i got the name of the value and not the integer.
0

You can try these

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

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.