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

查看:36
本文介绍了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 月 5 日)并且没有不适用于 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?

推荐答案

在你的模型中声明.

alias_attribute :new_column_name, :column_name_in_db

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

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