Rails 3 - Column Names (Legacy Database)

1.2k Views Asked by At

Possible Duplicate:
Alias for column names in Rails

I'm writing a module of ActiveRecord models to access a MySQL legacy database. My problem is that the database has a column naming convention that looks like this: groupID, metaGroupName, flagName. Is there an easy way to make the models play nice with this naming convention?

Update: I'd like to avoid the alias_attribute method if possible. It's not a small database, and that would be a lot of columns to alias. Is there a method in ActiveRecord that interprets column names that I can override, perhaps?

2

There are 2 best solutions below

1
On

You don't want to keep repeating yourself—that's good. Fortunately, Ruby makes it rather easy. Try something like the following:

class Model < ActiveRecord::Base

  column_names.each do |cn|
    alias_attribute cn.underscore.intern, cn
  end

end

I'd then factor that out into a Module maybe like so:

module AliasLegacyColumns
  extend ActiveSupport::Concern

  included do
    column_names.each {|cn|
      alias_attribute cn.underscore.intern, cn
    }
  end

end

Then just include that in your models as necessary. For further refinement I would provide an alias_columns class-level method that accepts parameters such as :include or :exclude so you can monkey-patch ActiveRecord::Base with said module but only call alias_columns as needed per model.

1
On

Just add the following to your model

alias_attribute :new_column_name, :myLegacyColumnName