【问题标题】:Ruby Rails - Querying Records with EnumerationsRuby Rails - 使用枚举查询记录
【发布时间】:2015-09-01 00:55:14
【问题描述】:

有一个表Fans 与列idcolor 使用枚举,以便{ "blue": 0, "yellow": 1 } 和数据库只存储整数值。

Fan.all.map {|fan| fan.attributes}

返回一个哈希数组,其中颜色仍为整数形式。如何获取颜色字段映射到文本的哈希数组?

【问题讨论】:

    标签: ruby-on-rails enums mapping


    【解决方案1】:

    Fan.colors 会给你哈希:{ "blue": 0, "yellow": 1 }

    和,

    my_fan = Fan.find(123)
    my_fan[:color] # Returns the integer value of color
    

    因此,要获取彩色文本,您可以像这样构建一个哈希:

    new_color_hash = { '0': "blue", "1": "yellow" }
    

    这很简单(只需将键与原始枚举哈希中的值交换)

    然后,当您循环访问Fan 属性时,只需调用:

    new_color_hash[my_fan[:color].to_s]
    

    获取此特定Fan 实例颜色的文本表示。

    这会起作用,尽管这不是一个很好看的实现。

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 2016-01-31
      • 2010-10-07
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多