1 ruby enums module ruby-on-rails
我的一个 Rails 模型中有以下模块:
module Color
RED = 0
BLUE = 1
YELLOW = 2
end
Run Code Online (Sandbox Code Playgroud)
我通过执行Color::RED等操作将这些值作为整数存储在数据库中。当我取回值时,我想获取字符串,即“红色”。但是我在转换 0 -> "RED"/"red" 时遇到问题。我错过了什么?我可以用模块方法来做到这一点还是有更好的方法?
由于您不能使用 Rails ActiveRecord enum,因此散列可能很有用:
COLORS = { "red" => 0, "blue" => 1, "yellow" => 2 }
Run Code Online (Sandbox Code Playgroud)
red_color = COLORS["red"] #red_color = 0
Run Code Online (Sandbox Code Playgroud)
COLORS.key(0)
# > "red"
Run Code Online (Sandbox Code Playgroud)
您甚至可以为此创建一个助手,例如:
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
Run Code Online (Sandbox Code Playgroud)