Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually set column name in rails model

I'm building a rails app around several existing databases, the column names used in the existing databases do not work well at all with the rails association conventions. Is there a way to set column name aliases in a model similar to the way you can

class User < Activerecord::Base
self.set_table_name "users"
end

Could I set column name aliases when the existing db columns will not work with default rails association naming conventions?

like image 674
OpenCoderX Avatar asked Mar 02 '12 15:03

OpenCoderX


3 Answers

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.

like image 118
yanyingwang Avatar answered Nov 19 '22 00:11

yanyingwang


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

class User < Activerecord::Base
  alias_attribute :new_column_name, :real_column_name
end
like image 41
Zheileman Avatar answered Nov 18 '22 23:11

Zheileman


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.

like image 2
coderates Avatar answered Nov 18 '22 22:11

coderates