Manually set column name in rails model

Recently I'm trying to refactor a project with Rails previously written by PHP and I encountered exactly the same thing.

After I hacked some Rails code, it turns out this is definitely can be done and it does need to modify lots of code to make it perfect, maybe it's for this reason and besides this is not a standard working way for Rails, so nobody implements it until now.

If you are interested in this, you can check out my code here: https://github.com/yanyingwang/active_columns_mapping

And as far as my consider this feature could be very useful for some special situation and it will be great if someone who is familiar enough with Rails core code do implement this feature.


If you are able to modify the database column (i.e. only your rails app is referencing it) you could write a migration using the rename_column method. Because you are using rails 3 you can simply use the following command

~: rails g migration RenameColumnNameToNewColumn columnName:columnType

Obviously replace the generic naming to what works best for you. This should create a migration for you that looks something like this, and if it doesn't, modify it to looks similar to the code below

 class ChangeOldColumnToNewColumn < ActiveRecord::Migration
      def up
          rename_column :tableName, :oldColumn, :newColumn
      end

      def down
          rename_column :tableName, :newColumn, :oldColumn
      end
 end

If you are not able to change the column name in the actual table you could place a line similar to this in your model which should achieve what you are trying to do.

alias_attribute :newColumnName, :existingColumnName

You may need to place existingColumnName within double quotes if the column name is confusing rails.


In your model, just setup alias for attributes (columns). For example:

class User < Activerecord::Base
  alias_attribute :new_column_name, :real_column_name
end