How to store enum as string to database in rails

Reading the enum documentation, you can see Rails use the value index of the Array explained as:

Note that when an Array is used, the implicit mapping from the values to database integers is derived from the order the values appear in the array.

But it is also stated that you can use a Hash:

it’s also possible to explicitly map the relation between attribute and database integer with a Hash.

With the example:

class Conversation < ActiveRecord::Base  
  enum status: { active: 0, archived: 1 }  
end

So I tested using Rails 4.2.4 and sqlite3 and created an User class with a string type for sex type and a Hash in the enum with string values(I am using fem and mal values to differ from female and male):

Migration:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :sex, default: 'fem'
    end
  end
end  

Model:

class User < ActiveRecord::Base
  enum sex: { female: 'fem', male: 'mal' }
end

And in console:

u = User.new
#=>  #<User id: nil, sex: "fem">
u.male?
#=> false
u.female?
#=> true
u.sex
#=> "female"
u[:sex]
#=> "fem"
u.male!
# INSERT transaction...
u.sex
#=> "male"
u[:sex]
#=> "mal"

Leave a Comment