- Make sure that enum name defined in model is same as database column
# model.rb
enum role: [:user, :vip, :admin, :developer, :marketing, :support, :translator]
<%# view.rb %>
<%= f.select(:role, User.roles.keys.map {|role| [role.titleize,role]}) %>
bin/rails generate Work nickname:string sex:integer
Then add a call to enum in the generated model file:
class Work < ActiveRecord::Base
enum sex: [ :male, :female ]
end
$ Phone.first.phone_number_type
> "fax"
$ phone.phone_number_type = 1; phone.phone_number_type
> "office"
$ phone.phone_number_type = "mobile"; phone.phone_number_type
> "mobile"
Or using bang method:
$ phone.office!
> true
$ phone.phone_number_type
> "office"
$ phone.office?
> true
$ Phone.office
> Phone Load (0.3ms) SELECT "phones".* FROM "phones" WHERE "phones"."phone_number_type" = ? [["phone_number_type", 1]]
If you want to see all the different values you can use, along with the numbers they’re associated with, use the phone_number_types class method:
$ Phone.phone_number_types
> {"home"=>0, "office"=>1, "mobile"=>2, "fax"=>3}
Which makes them easy to put into an HTML form:
<%# app/views/phones/_form.html.erb %>
<div class="field">
<%= f.label :phone_number_type %><br>
<%= f.select :phone_number_type, Phone.phone_number_types.keys %>
</div>
Form not saving as integer, try the following:
<%= f.select(:role, User.roles.map {|key, role| [key.titleize, role]}) %>