Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord enum returning nil, even if it has a value

I have an enum, which has a stored value, but the getter returns nil.

I have the following code:

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
  ]

If I do the following in the console:

Property.last

I get

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">

but If I do

Property.last.building_type

I get

 Property Load (0.5ms)  SELECT  "properties".* FROM "properties"   ORDER BY "properties"."id" DESC LIMIT 1
 => nil 
like image 748
Tony Avatar asked Nov 17 '14 19:11

Tony


1 Answers

It looks like your field type for the database entry of building_type is a String, instead of an Integer (which is what enum is mapping to according to the documents). Try to change the database schema and it should work.

like image 74
nikkon226 Avatar answered Sep 22 '22 01:09

nikkon226