Manually set column name in rails model

让人想犯罪 __ 提交于 2020-01-03 08:36:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!