As you read the enum documentation, you can see that Rails uses an index of Array values, which is explained as:
Note that when using an array, implicit matching of values with integers of the database comes from the order in which the values are displayed in the array.
But it also says that you can use Hash :
You can also explicitly match the relationship between the attribute and the integer number of the database with the hash.
In the example:
class Conversation < ActiveRecord::Base enum status: { active: 0, archived: 1 } end
So, I tested Rails 4.2.4 and sqlite3 and created a User class with type string for the type of gender and Hash in enum with string values (I use fem and small values are different from women and men):
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 the 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"
Doguita
source share