Last updated January 18, 2011 04:55, by qmxme
If your database connection adapter doesn't support a datatype you need by default, you can override the default datatype definitions with your own.
First, check to see what datatypes are already being extended in your adapter. I use MySQL, so I would look in the ActiveRecord-JDBC gem directory at <tt>lib/jdbc_adapter/jdbc_mysql.rb</tt>. At the top of the file is the following:
<pre>
module JdbcSpec
module MySQL
def modify_types(tp)
tp[:primary_key] = "int(11) DEFAULT NULL auto_increment PRIMARY KEY"
tp[:decimal] = { :name => "decimal" }
tp
end
</pre>
As we see here, the default datatype for a table's primary key is being defined. Also, it is defining the symbol :decimal to reference the MySQL "decimal" datatype (in the <tt>:name => "decimal"</tt> section.)
What we want to do is basically copy that into the <tt>environment.rb</tt> file in our Rails project, overriding the default modify_types method and adding in our own datatypes.
Since I, for example, want support for unsigned 64-bit integers (for both the primary key and for other columns) and large text fields, I would add the following to my <tt>environment.rb</tt> file:
<pre>
module JdbcSpec
module MySQL
def modify_types(tp)
tp[:primary_key] = "bigint unsigned DEFAULT NULL auto_increment PRIMARY KEY"
tp[:decimal] = { :name => "decimal" }
tp[:longtext] = { :name => "longtext" }
tp[:ubigint] = { :name => "bigint unsigned" }
tp
end
end
end
</pre>
With this in place, I can create a migration using my new datatypes:
<pre>
class CreateWidgets < ActiveRecord::Migration
def self.up
create_table :widgets do |t|
# t.column :name, :string
t.column :footext, :longtext
t.column :barnum, :ubigint
t.column :boringnormal, :string
end
end
def self.down
drop_table :widgets
end
end
</pre>
And after running <tt>rake db:migrate</tt>, I have the following table in my database:
<pre>
mysql> describe widgets;
+--------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------------+------+-----+---------+----------------+
| id | bigint(20) unsigned | NO | PRI | NULL | auto_increment |
| footext | longtext | YES | | NULL | |
| barnum | bigint(20) unsigned | YES | | NULL | |
| boringnormal | varchar(255) | YES | | NULL | |
+--------------+---------------------+------+-----+---------+----------------+
4 rows in set (0.01 sec)
</pre>





