[英]alias_attribute and creating and method with the original attribute name causes a loop
[英]Grab original method/column name from Rails alias_attribute
現在,我有一些帶有不同名稱列的舊類,這些類已通過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訪問舊名稱? 重命名舊列並不理想,因為該應用程序的許多其他部分仍在使用舊列名。
alias_attribute
是一個非常簡單的方法。 它所做的只是定義別名。
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
因此,無法檢索原始列名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.