19 December 2008

Native Postgresql Data Types for ActiveRecord

In researching ActiveRecord migrations, I came across this bit of new information in their documentation:

Instantiates a new column for the table. The type parameter is normally one of the migrations native types, which is one of the following: :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.

You may use a type not in this list as long as it is supported by your database (for example, "polygon" in MySQL), but this will not be database agnostic and should usually be avoided.

So, what? Well, this came in handy immediately because I was creating a table that used Postgresql's native inet data type. I plan to use some of the related inet functionality at a later date so this is a big win.

Here's an abbreviated version of my migration that uses the inet datatype. I am running Ruby on Rails 2.2.

class CreateDevices < ActiveRecord::Migration
def self.up
create_table :devices do |t|
t.column("ip_address", :inet) # this works beautifully
# t.inet :ip_address # this won't work


def self.down
drop_table :devices

Notice that one has to be explicit and use the column method and not the shortcut.

No comments:

Post a Comment