DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Rails Aliasing Of Database Column Names

08.05.2005
| 5009 views |
  • submit to reddit
        
Add to your model:

GreenPastures < ActiveRecord::Base

alias_column "new_name" => "crappy_old_nAmE"

Include this code in a file in /lib

module Legacy
  def self.append_features(base)
    super
    base.extend(ClassMethods)
  end
  module ClassMethods
    def alias_column(options)
      options.each do |new_name, old_name|
        self.send(:define_method, new_name) { self.send(old_name) }
        self.send(:define_method, "#{new_name}=") { |value| self.send("#{old_name}=", value) }
      end
    end
  end
end

ActiveRecord::Base.class_eval do
  include Legacy
end
    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:13pm

This is a fantastic, simple add-on. I wonder, however, if the aliasing is kind of backwards compared to the Ruby 'alias' keyword? alias new_name old_name seems to be the opposite of alias_column 'old_name' => 'new_name' Maybe reverse it?