Reputation:
I have the following module in one of my rails models:
module Color
RED = 0
BLUE = 1
YELLOW = 2
end
I store these values in a db as ints by doing Color::RED
etc. When I retrieve the values back I want to get the string, ie "red". But I am having trouble converting 0 -> "RED"/"red". What am I missing? Can I do this with the module approach or is there a better way?
Upvotes: 1
Views: 11339
Reputation: 5839
Since you cannot use Rails ActiveRecord enum
, then a hash might be useful:
COLORS = { "red" => 0, "blue" => 1, "yellow" => 2 }
red_color = COLORS["red"] #red_color = 0
COLORS.key(0)
# > "red"
You can even make a helper for that, something like:
def color_code_to_string(code)
COLORS.key(code) # returning a default color in case if wrong code number is a good idea too
end
Upvotes: 6