Enumeration type column in Ruby on Rails

August 27, 2010

  • Rails
  • Ruby
  • plugins
  • enumerations

Well another new functionality finally implemented.

It’s been two days for me trying to create an enum column in rails. Tried to do it by declaring the column type as enum. But its just that rails doesn’t implicitly support columns which have enum as data type.You can check the data types supported by rails here. I got frustrated when I wasn’t able to accomplish it on the first day. I got into a miscommunication with my TL upon using a plugin for implementing the enum-column where he told me not to use the plugin. Finally later that day I spoke to the TL once again and discussed the complete scenario once again. This time the miscommunication of the last time got cleared and we decided to use the plugin. And now after using this plugin I can add a column which provides support for using enum as a column in rails migration.

You can download the plugin enum-column using this plugin script:

script/plugin install svn://rubyforge.org/var/svn/enum-column/plugins/enum-column

If this doesn’t work you can directly download the latest *.zip file and unzip it in your vendor/plugins directory from rubyforge.org

Now after downloading the plugin you can finally use enumerations in rails. In your schema you can use

class CreateUsers < Activerecord::Migration
    def self.up
        create table :users do |t|
            t.enum :user_type ,:limit =>; [:admin, :user, :guest] ,:default =>; :guest
            t.string :username
        end
    end

    def self.down
        drop_table :users
    end
end

Now when the migration is up and running you can access it in the rest of the application. Now in users/new.html.erb you can use

<h1>New user</h1>
<% form_for(@user) do |f| %>
    <%= f.error_messages %>
    <p>
        <%= f.label :username %><br />
        <%= f.text_field :username %>
    </p>
    <p>
        <%= f.label :user_type %>
        <%= f.select :user_type, :collection => [:admin, :user, :guest] %>
    </p>
<% end %>

and do the same on the edit page. Thats all, we have the implemented enum-column successfully.


LOCATION

Mumbai, Maharashtra, India

AROUND THE WEB

Copyright © 2021