Reading ENUM attributes with Active Record

In order to export some records from a “legacy” database (ok, a very popular domain hosting product) I had to find a way to read out an ENUM fields. As Active Record doesn’t support this nonstandard MySQL specific type there is of course no auto generated getter method. Turns out supporting this was quite easy once I discovered the attributes_before_type_cast call in AR::Base. The MySQL column definition looks like this:

`type` enum('NS','A','CNAME','MX','PTR','TXT','none') NOT NULL default 'A'

The ActiveRecord getter method to fetch the type field looks this:

1
2
3
4
def record_type
  attr = attributes_before_type_cast
  "#{attr['type']}"
end

Actually, because ‘type’ is a reserved field name in AR the complete class looked like this:

1
2
3
4
5
6
7
8
class DnsRec < ActiveRecord::Base
  DnsRec.inheritance_column = 'sth_othr_thn_type'

  def record_type
    attr = attributes_before_type_cast
    "#{attr['type']}"
  end
end

How about writing ENUM fields? Not covered here, since IMHO it really is a bad idea :-)

This entry was posted in Home. Bookmark the permalink.

2 Responses to Reading ENUM attributes with Active Record

  1. Rik Hemsley says:

    Off-topic, sorry: There doesn’t seem to be a feed URL available for this blog. Any chance of sticking the link up, or do you want to be unsyndicated? Also, there’s no contact email address, hence the inappropriate comment.

    Cheers!

  2. andy says:

    Should be up now. Please try it :)