class Country < ActiveRecord::Base
#alias_method :name, :langEN # here fails
#alias_method :name=, :langEN=
#attr_accessible :name
def name; langEN end # here works
end
在第一次调用alias_method
失败时:
NameError: undefined method `langEN' for class `Country'
我的意思是当我做例如Country.first
时它失败了。
但是在控制台中我可以成功调用Country.first.langEN
,并看到第二个调用也可以。
我错过了什么?
ActiveRecord使用method_missing
(AFAIK via ActiveModel::AttributeMethods#method_missing
)在第一次调用时创建属性访问器和mutator方法。这意味着当您调用langEN
并且alias_method
因“未定义方法”错误而失败时,没有alias_method :name, :langEN
方法。明确地进行别名:
def name
langEN
end
是因为langEN
方法将在您第一次尝试调用时创建(由method_missing
创建)。
Rails提供alias_attribute
:
alias_attribute(new_name,old_name)
允许您为属性创建别名,包括getter,setter和query方法。
您可以使用它:
alias_attribute :name, :langEN
内置的method_missing
将了解使用alias_attribute
注册的别名,并根据需要设置适当的别名。