Changing the type on a legacy table in ActiveRecord

I’m doing some work for a client which involves extracting some data from a legacy database and displaying it in a web interface. One of the fields in the table is the number of megabytes included in the quota. For some crazy reason this is defined as follows:

CREATE TABLE quota (
  bandwidth_in_included DECIMAL(8,2)
);

This means that in the web interface I get 10,000.0 MB instead of 10,000 MB. Notice the decimal point. Also I wanted bytes rather than MB since the legacy app was a bit all over the place in this regard.

My first solution was to simple create a virtual attribute in the model to override the type.

class Quota < ActiveRecord::Base

  # We need it as an int and in bytes
  def bandwidth_in_included
    attributes['bandwidth_in_included].to_i * 1000
  end

end

This worked great except that I’m actually rendering the data to XML to be accessed over a REST service so this was generating XML elements like

10000

Eventually I discovered that you can tell ActiveRecord to override the type, so I ended up with

class Quota < ActiveRecord::Base

  # We want to treat the bandwidth_included a an integer
  class << columns_hash['bandwidth_in_included']
    def type
      :integer
    end 
  end 

  # We need it as an int and in bytes
  def bandwidth_in_included
    attributes['bandwidth_in_included].to_i * 1000
  end

end

Leave a Reply

Your email address will not be published. Required fields are marked *