Manually set the column name in the rails model

I am creating a rails application around several existing databases, the column names used in existing databases generally do not work with rail association conventions. Is there a way to set column name aliases in a model similar to how you can

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

Can I set column aliases if existing db columns do not work with standard default link naming conventions?

+6
source share
2 answers

In your model, just set up an alias for the attributes (columns). For instance:

 class User < Activerecord::Base alias_attribute :new_column_name, :real_column_name end 
+13
source

If you can change the database column (i.e. only your rails application refers to it), you can write the transfer using the rename_column method. Since you are using rails 3, you can simply use the following command

~: rails g migration RenameColumnNameToNewColumn columnName:columnType

Obviously, replace the generic designation with what is best for you. This should create a migration for you that looks something like this, and if it doesn't, change it to look like 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 can not change the column name in the actual table, you can put in your model a row like this, which should achieve what you are trying to do.

 alias_attribute :newColumnName, :existingColumnName 

You may need to put the existing column name in double quotation marks if the column name confuses the rails.

+2
source

Source: https://habr.com/ru/post/909837/


All Articles