Rails中的列名称的别名 [英] Alias for column names in Rails

查看:197
本文介绍了Rails中的列名称的别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的数据库中有列名称,如删除或监听控制等。这些不能更改,所以我想别名的名称,以避免在我的应用程序的问题。

In my database has column names such as 'delete' or 'listen-control' and so on. These cannot be changed, so I would like to alias the names so as to avoid problems in my application.

我发现以下代码,但它已过时(2005年8月05日),并且不能与Rails 3配合使用:

I found the following code but it is outdated (05 Aug 2005) and doesn't work with Rails 3:

module Legacy
  def self.append_features(base)
    super
    base.extend(ClassMethods)
  end
  module ClassMethods
    def alias_column(options)
      options.each do |new_name, old_name|
        self.send(:define_method, new_name) { self.send(old_name) }
        self.send(:define_method, "#{new_name}=") { |value| self.send("#{old_name}=", value) }
      end
    end
  end
end

ActiveRecord::Base.class_eval do
  include Legacy
end

如何对列名称进行别名?是否可能?

How can I alias the column names? Is it possible?

推荐答案

在模型中声明这一点。

Declare this in your model.

alias_attribute :new_column_name, :column_name_in_db

这篇关于Rails中的列名称的别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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