1

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?

Community
  • 1
  • 1
jtdoepke
  • 31
  • 2
  • 6

2 Answers2

2

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.

Alistair A. Israel
  • 6,417
  • 1
  • 31
  • 40
  • That works well. I have one more problem; I also added this alias for the primary key: `alias_attribute(:id, primary_key) unless primary_key.nil?`. But, if I try something like `LegacyModel.select(:id)`, I get a MySQL error that the 'id' column does not exist. It looks like Relation is not using the alias. It may be the problem described [here](http://stackoverflow.com/a/4433374/440292). `LegacyModel.find(some_id)` and `LegacyModel.first.id` both work. – jtdoepke Aug 02 '12 at 07:12
1

Just add the following to your model

alias_attribute :new_column_name, :myLegacyColumnName
Carl Mercier
  • 1,231
  • 1
  • 12
  • 10