为什么alias_method在Rails模型中失败

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通过ActiveModel::AttributeMethods#method_missing )在第一次调用它们时创建属性访问器和mutator方法。 这意味着当您调用alias_methodalias_method :name, :langEN时没有langEN方法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注册的别名,并将根据需要设置适当的别名。