Reading ENUM attributes with Active Record 2

Posted by andy

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 :-)
Comments

Leave a response

  1. Rik HemsleyOctober 24, 2005 @ 02:04 PM
    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. andyOctober 30, 2005 @ 09:43 PM
    Should be up now. Please try it :)
Comment