【问题标题】:Grab original method/column name from Rails alias_attribute从 Rails alias_attribute 获取原始方法/列名
【发布时间】:2017-10-05 04:17:42
【问题描述】:

现在,我有一些带有不同名称列的遗留类,我通过 Rails 的 alias_attribute 将它们别名为一个新的通用名称,如下所示:

class User < ActiveRecord::Base
  alias_attribute :id, :UserId
  ...
end

class Car < ActiveRecord::Base
  alias_attribute :id, :CarId
  ...
end

出于某些记录目的,我需要访问旧的列名(例如 CarId 和 UserId)。有没有一种通用的方法可以通过别名从 alias_attribute 访问旧名称?重命名旧列并不理想,因为应用程序的许多其他部分仍在使用旧列名。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    alias_attribute 是一个非常简单的方法。 All it does 是定义别名。

      def alias_attribute(new_name, old_name)
        # The following reader methods use an explicit `self` receiver in order to
        # support aliases that start with an uppercase letter. Otherwise, they would
        # be resolved as constants instead.
        module_eval <<-STR, __FILE__, __LINE__ + 1
          def #{new_name}; self.#{old_name}; end          # def subject; self.title; end
          def #{new_name}?; self.#{old_name}?; end        # def subject?; self.title?; end
          def #{new_name}=(v); self.#{old_name} = v; end  # def subject=(v); self.title = v; end
        STR
      end
    

    所以不,没有办法检索原始列名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 2013-06-11
      • 2016-09-14
      相关资源
      最近更新 更多