有没有一种方法来重新命名ActiveRecord模型列? [英] Is there a way to rename ActiveRecord model columns?

查看:135
本文介绍了有没有一种方法来重新命名ActiveRecord模型列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的想法选择导轨的ActiveRecord能够访问遗留数据库。它的名字是真的很混乱,所以它不会使用其列名在模型中是一个好主意。

I am thinking about choosing rails' ActiveRecord to have access to a legacy database. It's names are really confusing, so it wouldn't be a good idea to use its column names in the model.

设置表名是很容易。但我有办法重新命名列名,只是在型号?

Setting table name is really easy. But do I have a way to rename column name, only in the model?

约定优于配置是伟大的,但在这种情况下,我不能改变原有数据库的名称。

Convention over configuration is great, but in this case I can't change legacy database names.

使用alias_attribute从的ActiveSupport没有解决我的问题,因为对象仍然显示正在连载或打印时遗留下来的列名。我需要返回这些模型JSON格式,例如,和alias_attribute不会适用于本

Using alias_attribute from ActiveSupport doesn't solve my problem, since the object still shows the legacy column names when being serialized or printed. I need to return these models in JSON format, for instance, and alias_attribute wouldn't be suitable for this.

推荐答案

我做了什么来实现这一目标?

What did I do to achieve this?

在code以下覆盖默认加载ActiveModel ::序列化的 serializable_hash ,在将其转化列名。不完整的,也许有些重构将是很好的,但它的工作;)

The code below overwrites default ActiveModel::Serialization's serializable_hash, converting column names in it. Not complete, maybe some refactoring would be nice, but it's working ;)

模式例如:

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

这篇关于有没有一种方法来重新命名ActiveRecord模型列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆