Is there a way to rename columns of an ActiveRecord model?

I am thinking of choosing ActiveRecord for rails to access an outdated database. These names are really confusing, so it would be nice to use column names in the model.

Setting the table name is very simple. But is there a way to rename the column name, only in the model?

The consolidation of the configuration is excellent, but in this case I cannot change the names of the obsolete databases.

Using alias_attribute from ActiveSupport does not solve my problem, since the object still shows obsolete column names when they are serialized or printed. I need to return these models in JSON format, for example, and alias_attribute is not suitable for this.

+4
source share
2 answers

What have I done for this?

The code below overwrites the default value of ActiveModel :: Serialization serializable_hash , converting the column names to it. Not complete, maybe some refactoring will be nice, but it works;)

model example:

 class Account < ActiveRecord::Base include ActiveModel::ColumnNaming set_table_name 'conta_tbl' set_primary_key 'cod_conta' rename_columns ({ id: 'cod_conta', billing_group_id: 'id_cobranca', invoice_id: 'cod_pagamento' }) end 

code

 module ActiveModel module ColumnNaming extend ActiveSupport::Concern def serializable_hash(options = nil) hash = super(options) self.class.columns_map.each do |legacy, renamed| hash[renamed] = hash.delete(legacy) end hash end module ClassMethods def columns_map @columns_map end def rename_columns(map) @columns_map = map.invert columns_map.each { |key, value| alias_attribute value.to_sym, key.to_sym } end end end end 
+3
source

use alias_attribute in your model. eg.

 alias_attribute :new_column_name, :column_name_in_db 

for more information see fooobar.com/questions/109541 / ...

+3
source

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


All Articles