为什么alias_method在Rails模型中失败

jua*_*tas 24 ruby activerecord ruby-on-rails alias-method rails-activerecord

class Country < ActiveRecord::Base

  #alias_method :name, :langEN # here fails
  #alias_method :name=, :langEN=

  #attr_accessible :name

  def name; langEN end # here works
end
Run Code Online (Sandbox Code Playgroud)

在第一次呼叫alias_method失败时:

NameError: undefined method `langEN' for class `Country'
Run Code Online (Sandbox Code Playgroud)

我的意思是,当我这样做时,它失败了Country.first.

但是在控制台中我可以Country.first.langEN成功调用,并看到第二个调用也可以.

我错过了什么?

mu *_*ort 53

ActiveRecord 在第一次调用时使用method_missing(AFAIK via ActiveModel::AttributeMethods#method_missing)创建属性访问器和mutator方法.这意味着langEN当您调用时没有方法,alias_method并且alias_method :name, :langEN出现"未定义方法"错误.明确地进行别名:

def name
  langEN
end
Run Code Online (Sandbox Code Playgroud)

是因为该langEN方法将在method_missing您第一次尝试调用时创建(通过).

Rails提供alias_attribute:

alias_attribute(new_name,old_name)

允许您为属性创建别名,包括getter,setter和query方法.

您可以使用它:

alias_attribute :name, :langEN
Run Code Online (Sandbox Code Playgroud)

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