• Skip to primary navigation
  • Skip to main content

Inodes

Fractional CTO Consulting

  • Home
  • About Us
  • Contact Us
  • Block Examples
  • Landing Page
  • Pricing Page
  • Show Search
Hide Search

Changing the type on a legacy table in ActiveRecord

John Ferlito · 14 July 2009 · Leave a Comment

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:

SQL
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.

Ruby
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

XML
10000

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

Ruby
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

Programming

Reader Interactions

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Hit the ground running with a minimalist look. Learn More

Copyright © 2025 · Inodes Pty Ltd · Log in

  • Privacy Policy