【问题标题】:ActiveRecord enum returning nil, even if it has a valueActiveRecord 枚举返回 nil,即使它有一个值
【发布时间】:2015-01-14 19:07:18
【问题描述】:

我有一个枚举,它有一个存储值,但 getter 返回 nil。

我有以下代码:

class Property < ActiveRecord::Base
  enum building_type:   [
    :none_building_type, :pre_war_low_rise, :pre_war_mid_rise,
    :pre_war_high_rise, :post_war_low_rise, :post_war_mid_rise,
    :post_war_high_rise, :pre_war_loft, :post_war_loft, :pre_war_hotel,
    :post_war_hotel
  ]

如果我在控制台中执行以下操作:

Property.last

我明白了

Property Load (0.8ms)  SELECT  "properties".* FROM "properties"   ORDER BY "properties"."id" DESC LIMIT 1
 => #<Property id: 3, created_at: "2014-11-17 15:39:34", updated_at: "2014-11-17 16:28:48", name: "PropertyName", property_type: 1, description: "adsdsaads", building_type: "4">

如果我这样做了

Property.last.building_type

我明白了

 Property Load (0.5ms)  SELECT  "properties".* FROM "properties"   ORDER BY "properties"."id" DESC LIMIT 1
 => nil 

【问题讨论】:

    标签: ruby-on-rails ruby activerecord enums


    【解决方案1】:

    看起来building_type 的数据库条目的字段类型是字符串,而不是整数(这是enum 根据documents 映射到的内容)。尝试更改数据库架构,它应该可以工作。

    【讨论】:

    • 不错的收获@nikkon226!
    • @Anthony 总是(隐喻的)分号让你明白!
    • 希望我能给你一枚奖牌,即使在一百万年后我自己也想不通。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    • 2010-12-22
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多