为什么alias_method在Rails模型中失败

问题描述 投票:24回答:1
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,并看到第二个调用也可以。

我错过了什么?

ruby-on-rails ruby activerecord rails-activerecord alias-method
1个回答
52
投票

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注册的别名,并根据需要设置适当的别名。

© www.soinside.com 2019 - 2024. All rights reserved.