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 (通过 ActiveModel::AttributeMethods#method_missing 通过AFAIK)创建属性访问器和mutator方法。这意味着,当您调用 langEN 时,没有alias_method方法,而alias_method :name, :langEN失败,并显示“未定义方法”错误。明确地进行别名:

def name
  langEN
end

之所以有效,是因为首次尝试调用langEN方法时(会由method_missing创建)。

Rails提供 alias_attribute :



您可以改用:
alias_attribute :name, :langEN

内置的method_missing将知道向alias_attribute注册的别名,并将根据需要设置适当的别名。

10-05 20:44