Ruby on Rails 4.1
I am using Devise with enum role. It currently sets a defualt role when the User is created. I want to add a field to the form that creates Users to se
As enum is a wrapper for integer in Rails, and I wanted to store strings in DB instead, I did the following:
class Child < ApplicationRecord
enum year: {
Infant: 'Infant',
'2-5_years': '2_to_5_years',
'5-8_years': '5_to_8_years',
'8-10_years': '8_to_10 years',
'More_than_10_years': 'More_than_10_years'
}
AGE_YEARS = Child.years.map { |k, v| [k.humanize, v] }
}
In my form,
<%= f.select :age, options_for_select(Child::AGE_YEARS, params[:age]), include_blank: 'Select an age-group.' %>
As I was using PostGREsql server wherein a pre-defined datatype can be declared, I appended a column called 'year' to the Child model of type'year'.
rails generate migration AddYearToChildren year:year
and changed the migration file as below.
class AddYearToChildren < ActiveRecord::Migration[5.0]
def up
execute <<-SQL
CREATE TYPE year AS ENUM ('Infant', '2_5_years', '5_8_years', '8_10_years', 'More_than_10_years');
SQL
add_column :children, :year, :year, index: true
end
def down
remove_column :children, :year
execute <<-SQL
DROP TYPE year;
SQL
end
end
Finally, rails db:migrate
for DB migration changes.
So, now rails enum can be used to store strings in DB.