问题
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?
回答1:
In your model, just setup alias for attributes (columns). For example:
class User < Activerecord::Base
alias_attribute :new_column_name, :real_column_name
end
回答2:
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.
来源:https://stackoverflow.com/questions/9535989/manually-set-column-name-in-rails-model